/**
 *
 * @description Redux store , all the app state goes right here
 * * source : https://www.youtube.com/watch?v=Yokjzp91A4o
 */
import { TypedUseSelectorHook, useSelector } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import { persistStore, persistReducer, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import { combineReducers } from 'redux';
import authReducer from './features/auth-slice';
import themeTypeReducer from './features/theme-slice';
import alertReducer from './features/alert-slice';
import settingsReducer from './features/settings-slice';
import sidebarReducer from './features/sidebar-slice';
import servicesReducer from './features/services-slice';
import membersReducer from './features/members-slice';
import workersReducer from './features/workers-slice';
import productsReducer from './features/products-slice';
import statisticsReducer from './features/statistics-slice';
import equipmentsReducer from './features/equipments-slice';
import expensesReducer from './features/expenses-slice';
import incomesReducer from './features/incomes-slice';

// Combine all reducers
const rootReducer = combineReducers({
  authReducer, // handle auth states
  themeTypeReducer, // handle app theme
  alertReducer, // handle app alert
  settingsReducer, // handle the app settings
  sidebarReducer, // handle dashboard sidebar state
  servicesReducer, // handle the services page state
  membersReducer, // handle the members page state
  workersReducer, // handle the workers page state
  productsReducer, // handle the products page state
  statisticsReducer, // handle the statistics state
  equipmentsReducer, // handle the equipments state
  expensesReducer, // handle the expenses state
  incomesReducer, // handle the incomes state
});

// Persist config
const persistConfig = {
  key: 'root',
  version: 1,
  storage,
  whitelist: ['settingsReducer', 'authReducer', 'themeTypeReducer'], // Only persist these reducers
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

// Configure the store
export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
});

export const persistor = persistStore(store);

// Export types
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

// Export the store selector
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;