/**
 * 用户管理 Hooks
 * 使用 React Query 进行数据获取和缓存管理
 */

import { useQuery } from '@tanstack/react-query';
import { userService, type UserListParams } from '@/services/userService';

/** Query Keys */
export const userKeys = {
  all: ['users'] as const,
  list: (params: UserListParams) => [...userKeys.all, 'list', params] as const,
  detail: (id: string) => [...userKeys.all, 'detail', id] as const,
  stats: () => [...userKeys.all, 'stats'] as const,
};

/**
 * 获取用户列表
 * 注意：apiClient 响应拦截器已解包 response.data，直接返回数据
 */
export function useUsers(params: UserListParams = {}) {
  return useQuery({
    queryKey: userKeys.list(params),
    queryFn: () => userService.getUsers(params),
    staleTime: 30 * 1000, // 30秒后标记为过期
    gcTime: 5 * 60 * 1000, // 5分钟后垃圾回收
  });
}

/**
 * 获取用户详情
 */
export function useUserDetail(id: string) {
  return useQuery({
    queryKey: userKeys.detail(id),
    queryFn: () => userService.getUserDetail(id),
    enabled: !!id, // 只有在 id 存在时才查询
    staleTime: 60 * 1000, // 1分钟后标记为过期
    gcTime: 5 * 60 * 1000,
  });
}

/**
 * 获取用户统计
 */
export function useUserStats() {
  return useQuery({
    queryKey: userKeys.stats(),
    queryFn: () => userService.getUserStats(),
    staleTime: 60 * 1000, // 1分钟后标记为过期
    gcTime: 5 * 60 * 1000,
  });
}
