import { lens } from '@dhmk/zustand-lens';
import { SetStateAction } from 'react';
import { UserFavorite, UserInfo } from './types';
import { StorageKeys } from '@/shared/constants/local-storage';

export interface UserInfoState {
  userInfo: UserInfo;
  setUserInfo: (update: SetStateAction<Partial<UserInfo>>) => void;
  resetUserInfo: () => void;
  userFavorite: Array<UserFavorite>;
  setUserFavorite: (update: SetStateAction<Array<UserFavorite>>) => void;
};

const initialUserInfoState = {
  userInfo: {} as UserInfo,
  userFavorite: [] as Array<UserFavorite>
} as UserInfoState;

export const createUserInfoStore = lens<UserInfoState>((set, get) => ({
  ...initialUserInfoState,
  setUserInfo: (update) => {
    set((state: UserInfoState) => {
      const newUserInfo = (typeof update === 'function')
        ? update(state.userInfo): update;
      return {
        ...state,
        userInfo: {
          ...state.userInfo,
          ...newUserInfo
        },
      };
    });
  },
  resetUserInfo: () => {
    window.localStorage.removeItem(StorageKeys.TokenType);
    window.localStorage.removeItem(StorageKeys.AccessToken);
    window.localStorage.removeItem(StorageKeys.RefreshToken);
    window.localStorage.removeItem(StorageKeys.AccessTokenExpiresIn);
    window.localStorage.removeItem(StorageKeys.RefreshTokenExpiresIn);
    window.localStorage.removeItem(StorageKeys.MenuGrants);
    window.localStorage.removeItem(StorageKeys.Usrid);
    // window.localStorage.removeItem(StorageKeys.ClientAddressIP);
    // window.localStorage.removeItem(StorageKeys.Requires2FA);
    set(initialUserInfoState);
  },
  setUserFavorite: (update) => {
    set((state: UserInfoState) => {
      const newUserFavorite = (typeof update === 'function')
        ? update(state.userFavorite): update;
      return {
        ...state,
        userFavorite: {
          ...state.userFavorite,
          ...newUserFavorite
        },
      };
    });
  },
}));
