import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { createWrapper, Context } from "next-redux-wrapper";
import { persistStore, persistReducer, Persistor } from "redux-persist";
import storage from "redux-persist/lib/storage"; // uses localStorage
import counterReducer from "./slices/counterSlice";
import authSlice from "./slices/authSlice";
import addressSlice from "./slices/addressSlice";
import wishlistSlice from "./slices/wishlistSlice";
import recentlyViewedSlice from "./slices/recentlyViewedSlice";
import buyerOrdersSlice from "./slices/orders/buyerOrderSlice";
import sellerOrdersSlice from "./slices/orders/sellerOrderSlice";

// Define persist config
const persistConfig = {
  key: "user_data",
  storage,
  whitelist: ["auth", "address", "wishlist", "recentlyViewed", "buyerOrders", "sellerOrders"],
};

// Combine reducers
const rootReducer = combineReducers({
  counter: counterReducer,
  auth: authSlice,
  address: addressSlice,
  wishlist: wishlistSlice,
  recentlyViewed: recentlyViewedSlice,
  buyerOrders: buyerOrdersSlice,
  sellerOrders: sellerOrdersSlice
});

const persistedReducer = persistReducer(persistConfig, rootReducer);

// Define the store type
export const makeStore = () => {
  return configureStore({
    reducer: persistedReducer,
    devTools: process.env.NODE_ENV !== "production",
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware({
        serializableCheck: false, // Needed for redux-persist
      }),
  });
};

export const store = makeStore();
export const persistor: Persistor = persistStore(store);

// Infer the `RootState` and `AppDispatch` types
export type AppStore = ReturnType<typeof makeStore>;
export type RootState = ReturnType<AppStore["getState"]>;
export type AppDispatch = AppStore["dispatch"];

export const wrapper = createWrapper<AppStore>(makeStore, { debug: true });
