import {UserLoginData} from '@models';
import {QueryCache} from '@tanstack/react-query';
import {USER_TOKEN_STORAGE} from '@utils';
import {startTransition} from 'react';
import {createStore} from 'zustand/vanilla';

type UserStoreState = UserLoginData;

type UserStoreAction = {
  init(data: UserLoginData): void;
  logout(): void;
  setMenu(menus: string[]): void;
};

function defaultValue(): UserStoreState {
  return {
    id: 0,
    realName: '',
    token: '',
    userName: '',
    menu: null,
  };
}

export const userStore = createStore<UserStoreState & UserStoreAction>(function(set) {
  // 刷新时不会丢掉用户状态
  const sessionData = sessionStorage.getItem(USER_TOKEN_STORAGE);
  const initValue = sessionData ? JSON.parse(sessionData) as UserLoginData : defaultValue();

  return {
    ...initValue,
    init(data) {
      set(data);
    },
    logout() {
      sessionStorage.removeItem(USER_TOKEN_STORAGE);
      set(defaultValue());
      startTransition(function() {
        const queryCache = new QueryCache();
        queryCache.clear();
      });
    },
    setMenu(menus) {
      set({menu: menus.join(',') + ','});
    },
  };
});
