/**
 * 认证服务
 * 处理登录、登出等认证相关操作
 */

import { localStorageService, STORAGE_KEYS } from '@/infrastructure/storage/localStorage';
import { sessionStorageService } from '@/infrastructure/storage/sessionStorage';
import { store } from '@/store/redux/store';
import { logout as logoutAction } from '@/store/redux/slices/authSlice';
import { useUserFiltersStore } from '@/store/zustand/useUserFiltersStore';
import { useLeaderboardStore } from '@/store/zustand/useLeaderboardStore';
import { useModalStore } from '@/store/zustand/useModalStore';

/**
 * 安全退出登录
 * 清除所有用户相关的上下文和存储
 */
export const logoutService = {
  /**
   * 执行完整的退出登录流程
   */
  logout: () => {
    // 1. 清除 Redux 状态
    store.dispatch(logoutAction());

    // 2. 清除 Zustand stores
    useUserFiltersStore.getState().resetFilters();
    useLeaderboardStore.setState({
      activeBoard: 'daily',
      virtualSettings: {
        enabled: false,
        virtualAccountCount: 0,
        ruleDescription: '',
      },
      displaySettings: {
        frontendDisplayCount: 10,
      },
    });
    useModalStore.getState().closeModal();

    // 3. 清除 localStorage 中的认证信息
    localStorageService.remove(STORAGE_KEYS.TOKEN);
    localStorageService.remove(STORAGE_KEYS.USER);

    // 4. 清除 sessionStorage 中的会话数据
    sessionStorageService.clear();
  },

  /**
   * 检查是否已登录
   */
  isAuthenticated: (): boolean => {
    const token = localStorageService.get<string>(STORAGE_KEYS.TOKEN);
    return !!token;
  },

  /**
   * 获取当前 token
   */
  getToken: (): string | null => {
    return localStorageService.get<string>(STORAGE_KEYS.TOKEN);
  },
};

export default logoutService;
