/**
 * 用户状态 Zustand Store
 * 管理当前用户和其他用户信息
 */

import { create } from 'zustand';
import type { UserDTO } from '../../types/dto';
import { CacheEntry, createCacheEntry, isCacheExpired, DEFAULT_TTL } from '../utils/cache';

// ==================== 状态接口 ====================

export interface UserManagerState {
  // 当前用户
  currentUser: UserDTO | null;
  currentUserEntry: CacheEntry<UserDTO | null> | null;

  // 其他用户缓存
  usersMap: Map<string, CacheEntry<UserDTO | null>>;

  // 加载状态
  isLoadingCurrentUser: boolean;
  loadingUserIds: Set<string>;

  // 待处理请求（去重）
  pendingRequests: Map<string, Promise<any>>;
}

export interface UserManagerActions {
  // 获取状态
  getCurrentUser: () => UserDTO | null;
  getUser: (userId: string) => UserDTO | null;
  isCurrentUserExpired: () => boolean;
  isUserExpired: (userId: string) => boolean;
  isLoadingUser: (userId: string) => boolean;

  // 设置状态
  setCurrentUser: (user: UserDTO | null) => void;
  setCurrentUserEntry: (entry: CacheEntry<UserDTO | null>) => void;
  setUser: (userId: string, user: UserDTO | null) => void;
  setLoadingCurrentUser: (loading: boolean) => void;
  setLoadingUser: (userId: string, loading: boolean) => void;

  // 缓存管理
  invalidateCurrentUser: () => void;
  invalidateUser: (userId: string) => void;
  invalidateAll: () => void;

  // 请求去重
  getPendingRequest: <T>(key: string) => Promise<T> | undefined;
  setPendingRequest: <T>(key: string, request: Promise<T>) => void;
  deletePendingRequest: (key: string) => void;
  clearPendingRequests: () => void;

  // 重置
  reset: () => void;
}

// ==================== 初始状态 ====================

const initialState: UserManagerState = {
  currentUser: null,
  currentUserEntry: null,
  usersMap: new Map(),
  isLoadingCurrentUser: false,
  loadingUserIds: new Set(),
  pendingRequests: new Map(),
};

// ==================== Store 创建 ====================

export type UserManagerStore = UserManagerState & UserManagerActions;

export const useUserManagerStore = create<UserManagerStore>((set, get) => ({
  // ==================== 初始状态 ====================
  ...initialState,

  // ==================== 获取状态 ====================

  getCurrentUser: () => {
    const entry = get().currentUserEntry;
    if (!entry) return null;
    if (isCacheExpired(entry)) return null;
    return entry.data;
  },

  getUser: (userId: string) => {
    const entry = get().usersMap.get(userId);
    if (!entry) return null;
    if (isCacheExpired(entry)) return null;
    return entry.data;
  },

  isCurrentUserExpired: () => {
    const entry = get().currentUserEntry;
    if (!entry) return true;
    return isCacheExpired(entry);
  },

  isUserExpired: (userId: string) => {
    const entry = get().usersMap.get(userId);
    if (!entry) return true;
    return isCacheExpired(entry);
  },

  isLoadingUser: (userId: string) => {
    return get().loadingUserIds.has(userId);
  },

  // ==================== 设置状态 ====================

  setCurrentUser: (user: UserDTO | null) => {
    set({
      currentUser: user,
      currentUserEntry: createCacheEntry(user, DEFAULT_TTL.USER),
    });
  },

  setCurrentUserEntry: (entry: CacheEntry<UserDTO | null>) => {
    set({
      currentUser: entry.data,
      currentUserEntry: entry,
    });
  },

  setUser: (userId: string, user: UserDTO | null) => {
    set(state => {
      const newUsersMap = new Map(state.usersMap);
      newUsersMap.set(userId, createCacheEntry(user, DEFAULT_TTL.USER));
      return { usersMap: newUsersMap };
    });
  },

  setLoadingCurrentUser: (loading: boolean) => {
    set({ isLoadingCurrentUser: loading });
  },

  setLoadingUser: (userId: string, loading: boolean) => {
    set(state => {
      const newLoadingUserIds = new Set(state.loadingUserIds);
      if (loading) {
        newLoadingUserIds.add(userId);
      } else {
        newLoadingUserIds.delete(userId);
      }
      return { loadingUserIds: newLoadingUserIds };
    });
  },

  // ==================== 缓存管理 ====================

  invalidateCurrentUser: () => {
    set({
      currentUser: null,
      currentUserEntry: null,
    });
  },

  invalidateUser: (userId: string) => {
    set(state => {
      const newUsersMap = new Map(state.usersMap);
      newUsersMap.delete(userId);
      return { usersMap: newUsersMap };
    });
  },

  invalidateAll: () => {
    set({
      currentUser: null,
      currentUserEntry: null,
      usersMap: new Map(),
      pendingRequests: new Map(),
    });
  },

  // ==================== 请求去重 ====================

  getPendingRequest: <T>(key: string) => {
    return get().pendingRequests.get(key) as Promise<T> | undefined;
  },

  setPendingRequest: <T>(key: string, request: Promise<T>) => {
    set(state => {
      const newPendingRequests = new Map(state.pendingRequests);
      newPendingRequests.set(key, request);
      return { pendingRequests: newPendingRequests };
    });
  },

  deletePendingRequest: (key: string) => {
    set(state => {
      const newPendingRequests = new Map(state.pendingRequests);
      newPendingRequests.delete(key);
      return { pendingRequests: newPendingRequests };
    });
  },

  clearPendingRequests: () => {
    set({ pendingRequests: new Map() });
  },

  // ==================== 重置 ====================

  reset: () => {
    set({
      ...initialState,
      usersMap: new Map(),
      loadingUserIds: new Set(),
      pendingRequests: new Map(),
    });
  },
}));