// index.ts
import {
  combineReducers,
  configureStore,
  getDefaultMiddleware,
} from '@reduxjs/toolkit';
import { createWrapper } from 'next-redux-wrapper';
import { persistReducer, persistStore } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import addressReducer from './module/address';
import globalDataReducer from './module/globalData';
import systemReducer from './module/system';
import userInfoReducer from './module/userInfo';

// 单独创建rootReducer供服务端和客户端创建store使用；
const rootReducer = combineReducers({
  userInfo: userInfoReducer,
  address: addressReducer,
  system: systemReducer,
  globalData: globalDataReducer,
});

const makeStore = () => {
  const isServer = typeof window === 'undefined';
  // 区分客户端和服务端，服务端不需要持久存储，客户端存在在localStorage中；
  if (isServer) {
    return configureStore({
      reducer: rootReducer,
      devTools: true,
    });
  }
  const persistConfig = {
    key: 'SHAREFLY-WEB-STORAGE',
    whiteList: ['userInfo', 'address', 'system'],
    blacklist: ['globalData'],
    storage,
  };
  const persistedReducer = persistReducer(persistConfig, rootReducer);
  const store = configureStore({
    reducer: persistedReducer,
    devTools: process.env.NODE_ENV !== 'production',
    middleware: getDefaultMiddleware({
      serializableCheck: false, // 添加这一行
    }),
  });
  // @ts-ignore 只使用客户端渲染不需要此种做法，只需导出persistor即可；
  // eslint-disable-next-line no-underscore-dangle
  (store as any).__persistor = persistStore(store);
  return store;
};

export type AppStore = ReturnType<typeof makeStore>;
export type RootState = ReturnType<AppStore['getState']>;
export const wrapper = createWrapper(makeStore);
