// user.ts
import { createSlice } from '@reduxjs/toolkit';
import { HYDRATE } from 'next-redux-wrapper';
import { InterDataType } from '@/api/interface';
import { UserAddressSelectList } from '@/api/interface/user';

export type GlobalDataState = {
  loginModalVisible: boolean;
  userAddressList?: InterDataType<UserAddressSelectList>;
  userAddressSelectId?: number;
  productSpecNum?: number;
};

const initialState: GlobalDataState = {
  loginModalVisible: false,
  userAddressList: undefined,
  userAddressSelectId: undefined,
  productSpecNum: undefined,
};

const globalDataSlice = createSlice({
  name: 'globalData',
  initialState,
  reducers: {
    setGlobalData: (state, action) => {
      return { ...state, ...action.payload };
    },
  },
  extraReducers: {
    // hydrated 用于获取服务端注入的state并选择更新
    [HYDRATE]: (state, action) => {
      return {
        ...state,
        ...action.payload.globalData,
      };
    },
  },
});

export const { setGlobalData } = globalDataSlice.actions;
export default globalDataSlice.reducer;
