// @/api/modules/user.ts
import request from '@/api'
import type { PageParams, PageResult } from '@/types/api'

// ============================================
// 类型定义
// ============================================

export interface User {
  id: string
  name: string
  email: string
  avatar?: string
  status: 'active' | 'disabled'
  role: 'admin' | 'user' | 'guest'
  createdAt: string
  updatedAt: string
}

export interface CreateUserDto {
  name: string
  email: string
  password: string
  role?: User['role']
}

export interface UpdateUserDto {
  name?: string
  email?: string
  status?: User['status']
  role?: User['role']
}

export interface UserListParams extends PageParams {
  search?: string
  status?: User['status']
  role?: User['role']
}

// ============================================
// API 封装
// ============================================

export const userApi = {
  /**
   * 获取用户分页列表
   */
  getPage: (params: UserListParams) =>
    request.get<PageResult<User>>('/users', { params }),

  /**
   * 获取用户列表（无分页，用于下拉选择等场景）
   */
  getList: (params?: Partial<UserListParams>) =>
    request.get<User[]>('/users/list', { params }),

  /**
   * 获取用户详情
   */
  getById: (id: string) =>
    request.get<User>(`/users/${id}`),

  /**
   * 检查邮箱是否已存在
   */
  checkEmail: (email: string) =>
    request.get<{ exists: boolean }>('/users/check-email', { params: { email } }),

  /**
   * 创建用户
   */
  create: (data: CreateUserDto) =>
    request.post<User>('/users', data),

  /**
   * 更新用户
   */
  update: (id: string, data: UpdateUserDto) =>
    request.put<User>(`/users/${id}`, data),

  /**
   * 删除用户
   */
  remove: (id: string) =>
    request.delete<void>(`/users/${id}`),

  /**
   * 批量删除用户
   */
  batchRemove: (ids: string[]) =>
    request.post<void>('/users/batch-delete', { ids }),

  /**
   * 启用/禁用用户
   */
  toggleStatus: (id: string, status: User['status']) =>
    request.patch<User>(`/users/${id}/status`, { status }),

  /**
   * 重置用户密码
   */
  resetPassword: (id: string) =>
    request.post<{ tempPassword: string }>(`/users/${id}/reset-password`),

  /**
   * 导出用户列表
   */
  export: (params?: UserListParams) =>
    request.get<Blob>('/users/export', {
      params,
      responseType: 'blob',
    }),
}
