// index.ts
import { combineReducers, configureStore } 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 './address';
import userReducer from './user';

// 单独创建rootReducer供服务端和客户端创建store使用；
const rootReducer = combineReducers({
  user: userReducer,
  address: addressReducer,
});

const makeStore = () => {
  const isServer = typeof window === 'undefined';
  // 区分客户端和服务端，服务端不需要持久存储，客户端存在在localStorage中；
  if (isServer) {
    return configureStore({
      reducer: rootReducer,
      devTools: true,
    });
  }
  const persistConfig = {
    key: 'SHAREFLY-WEB-STORAGE',
    whiteList: ['user', 'address'],
    storage,
  };
  const persistedReducer = persistReducer(persistConfig, rootReducer);
  const store = configureStore({
    reducer: persistedReducer,
    devTools: process.env.NODE_ENV !== 'production',
  });
  // @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);
