import { request, type ApiResponse } from '@/utils/request'

// ============ Captcha Types ============

// 验证码响应
export interface CaptchaResponse {
  captchaKey: string
  captchaImage: string  // base64 encoded image
}

// ============ Login Types ============

// 登录请求 (扩展支持验证码)
export interface LoginRequest {
  username: string
  password: string
  captchaKey?: string
  captchaCode?: string
}

// 用户信息
export interface UserInfo {
  id: number
  username: string
  realName: string | null
  avatar: string | null
  email: string | null
  phone: string | null
  departmentId: number | null
  departmentName: string | null
  roles: string[]
  permissions: string[]
}

// 登录响应 (扩展支持双Token)
export interface LoginResponse {
  accessToken: string
  refreshToken: string
  expiresIn: number
  userInfo: UserInfo
  // Legacy field for backward compatibility
  token?: string
}

// ============ Token Refresh Types ============

// 刷新Token请求
export interface RefreshTokenRequest {
  refreshToken: string
}

// 刷新Token响应
export interface RefreshTokenResponse {
  accessToken: string
  refreshToken: string
  expiresIn: number
}

// ============ Password Types ============

// 修改密码请求
export interface ChangePasswordRequest {
  oldPassword: string
  newPassword: string
}

// ============ API Functions ============

/**
 * 获取验证码
 */
export function getCaptcha(): Promise<ApiResponse<CaptchaResponse>> {
  return request({
    url: '/admin/auth/captcha',
    method: 'post'
  })
}

/**
 * 登录
 */
export function login(data: LoginRequest): Promise<ApiResponse<LoginResponse>> {
  return request({
    url: '/admin/auth/login',
    method: 'post',
    data
  })
}

/**
 * 刷新Token
 */
export function refreshToken(token: string): Promise<ApiResponse<RefreshTokenResponse>> {
  return request({
    url: '/admin/auth/refresh',
    method: 'post',
    data: { refreshToken: token }
  })
}

/**
 * 获取当前用户信息
 */
export function getUserInfo(): Promise<ApiResponse<UserInfo>> {
  return request({
    url: '/admin/auth/info',
    method: 'get'
  })
}

/**
 * 修改密码
 */
export function changePassword(data: ChangePasswordRequest): Promise<ApiResponse<void>> {
  return request({
    url: '/admin/auth/password',
    method: 'put',
    data
  })
}

/**
 * 退出登录
 */
export function logout(): Promise<ApiResponse<void>> {
  return request({
    url: '/admin/auth/logout',
    method: 'post'
  })
}

/**
 * 撤销用户所有Token（强制下线所有设备）
 */
export function revokeAllTokens(): Promise<ApiResponse<void>> {
  return request({
    url: '/admin/auth/revoke-all',
    method: 'post'
  })
}
