import { lens } from '@dhmk/zustand-lens';
import { SetStateAction } from 'react';
import { UserInfo } from '@/entities/user/model/types';
import { StorageKeys } from '~/shared/constants/local-storage';

export interface UserInfoState {
  UserInfo: UserInfo;
  setUserInfo: (update: SetStateAction<Partial<UserInfo>>) => void;
  resetUserInfo: () => void;
}

const initialState = {
  UserInfo: {} as UserInfo,
} as UserInfoState;

export const createUserInfoStore = lens<UserInfoState>((set, get) => ({
  ...initialState,
  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(initialState);
  },
}));
