import { configureStore } from "@reduxjs/toolkit";
import appReducer from "./appActions";
import authReducer from "./authSlice";
import profileReducer from "./profileSlice";
import matchReducer from "./matchProfileSlice";
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";
import storage from "redux-persist/lib/storage";
import { InitialState } from "./authSlice";

const authPersistConfig = {
  key: "auth",
  storage,
  whitelist: ["email", "isLoggedIn", "userToken"],
};

const persistedAuthReducer = persistReducer<InitialState>(
  authPersistConfig,
  authReducer
);

const rootReducer = (state: any, action: any) => {
  // Clear all redux state
  if (action.type === PURGE) {
    storage.removeItem("persist:auth");
    return {
      counter: appReducer(undefined, action),
      auth: authReducer(undefined, action),
      profile: profileReducer(undefined, action),
      match: matchReducer(undefined, action),
    };
  }

  return {
    counter: appReducer(state?.counter, action),
    auth: persistedAuthReducer(state?.auth, action),
    profile: profileReducer(state?.profile, action),
    match: matchReducer(state?.match, action),
  };
};

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

export const persistor = persistStore(store);

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
