// 认证相关API接口
import { ApiRequest } from '../request'
import type {
  ApiResponse,
  User,
  LoginRequest,
  LoginResponse,
  BackendLoginResponse,
  RegisterRequest,
  UserProfile,
} from '../types'

/**
 * 认证API模块
 */
export class AuthApi {
  // 用户登录
  static async login(data: LoginRequest): Promise<ApiResponse<LoginResponse>> {
    try {
      // 调用后端API
      const response = await ApiRequest.post<BackendLoginResponse>('/users/login', data)

      // 适配后端响应格式为前端期望的格式
      const adaptedResponse: ApiResponse<LoginResponse> = {
        code: response.code,
        message: response.message,
        data: {
          user: {
            id: response.data.id, // 使用后端返回的用户ID
            email: data.email || '',
            phone: data.phone || '',
            username: data.phone || data.email?.split('@')[0] || 'user',
            nickname: '用户',
            avatar: '',
            role: 'student',
            status: 'active',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          },
          token: response.data.token,
          refreshToken: '', // 后端没有返回，使用空字符串
          expiresIn: 3600 // 默认1小时，可以根据expires字段计算
        }
      }

      return adaptedResponse
    } catch (error) {
      throw error
    }
  }

  // 用户注册
  static register(data: RegisterRequest): Promise<ApiResponse<User>> {
    return ApiRequest.post('/auth/register', data)
  }

  // 用户登出
  static logout(): Promise<ApiResponse<null>> {
    return ApiRequest.post('/auth/logout')
  }

  // 刷新Token
  static refreshToken(refreshToken: string): Promise<ApiResponse<LoginResponse>> {
    return ApiRequest.post('/auth/refresh', { refreshToken })
  }

  // 获取当前用户信息
  static getCurrentUser(): Promise<ApiResponse<User>> {
    return ApiRequest.get('/auth/me')
  }

  // 更新用户资料
  static updateProfile(data: Partial<UserProfile>): Promise<ApiResponse<User>> {
    return ApiRequest.put('/auth/profile', data)
  }

  // 修改密码
  static changePassword(data: {
    oldPassword: string
    newPassword: string
    confirmPassword: string
  }): Promise<ApiResponse<null>> {
    return ApiRequest.post('/auth/change-password', data)
  }

  // 忘记密码 - 发送重置邮件
  static forgotPassword(email: string): Promise<ApiResponse<null>> {
    return ApiRequest.post('/auth/forgot-password', { email })
  }

  // 重置密码
  static resetPassword(data: {
    token: string
    password: string
    confirmPassword: string
  }): Promise<ApiResponse<null>> {
    return ApiRequest.post('/auth/reset-password', data)
  }

  // 发送邮箱验证码
  static sendEmailVerification(email: string): Promise<ApiResponse<null>> {
    return ApiRequest.post('/auth/send-email-verification', { email })
  }

  // 验证邮箱
  static verifyEmail(data: {
    email: string
    code: string
  }): Promise<ApiResponse<null>> {
    return ApiRequest.post('/auth/verify-email', data)
  }

  // 发送手机验证码
  static sendSmsVerification(phone: string): Promise<ApiResponse<null>> {
    return ApiRequest.post('/auth/send-sms-verification', { phone })
  }

  // 验证手机号
  static verifyPhone(data: {
    phone: string
    code: string
  }): Promise<ApiResponse<null>> {
    return ApiRequest.post('/auth/verify-phone', data)
  }

  // 绑定第三方账号
  static bindThirdParty(data: {
    provider: 'wechat' | 'qq' | 'weibo' | 'github'
    code: string
    state?: string
  }): Promise<ApiResponse<User>> {
    return ApiRequest.post('/auth/bind-third-party', data)
  }

  // 解绑第三方账号
  static unbindThirdParty(provider: string): Promise<ApiResponse<null>> {
    return ApiRequest.delete(`/auth/unbind-third-party/${provider}`)
  }

  // 获取第三方登录URL
  static getThirdPartyLoginUrl(provider: string, redirectUrl?: string): Promise<ApiResponse<{ url: string }>> {
    return ApiRequest.get(`/auth/third-party-login-url/${provider}`, { redirectUrl })
  }

  // 第三方登录回调
  static thirdPartyLoginCallback(data: {
    provider: string
    code: string
    state?: string
  }): Promise<ApiResponse<LoginResponse>> {
    return ApiRequest.post('/auth/third-party-login-callback', data)
  }

  // 上传头像
  static uploadAvatar(file: File, onProgress?: (progress: number) => void): Promise<ApiResponse<{ url: string }>> {
    return ApiRequest.upload('/auth/upload-avatar', file, onProgress)
  }

  // 删除账号
  static deleteAccount(password: string): Promise<ApiResponse<null>> {
    return ApiRequest.post('/auth/delete-account', { password })
  }

  // 获取账号安全信息
  static getSecurityInfo(): Promise<ApiResponse<{
    hasPassword: boolean
    hasEmail: boolean
    hasPhone: boolean
    emailVerified: boolean
    phoneVerified: boolean
    twoFactorEnabled: boolean
    thirdPartyAccounts: Array<{
      provider: string
      nickname: string
      avatar?: string
      bindTime: string
    }>
    loginHistory: Array<{
      ip: string
      location: string
      device: string
      loginTime: string
    }>
  }>> {
    return ApiRequest.get('/auth/security-info')
  }

  // 启用两步验证
  static enableTwoFactor(): Promise<ApiResponse<{
    qrCode: string
    secret: string
    backupCodes: string[]
  }>> {
    return ApiRequest.post('/auth/enable-two-factor')
  }

  // 确认启用两步验证
  static confirmTwoFactor(code: string): Promise<ApiResponse<{
    backupCodes: string[]
  }>> {
    return ApiRequest.post('/auth/confirm-two-factor', { code })
  }

  // 禁用两步验证
  static disableTwoFactor(data: {
    password: string
    code: string
  }): Promise<ApiResponse<null>> {
    return ApiRequest.post('/auth/disable-two-factor', data)
  }

  // 生成新的备用码
  static generateBackupCodes(): Promise<ApiResponse<{
    backupCodes: string[]
  }>> {
    return ApiRequest.post('/auth/generate-backup-codes')
  }

  // 验证两步验证码
  static verifyTwoFactor(code: string): Promise<ApiResponse<null>> {
    return ApiRequest.post('/auth/verify-two-factor', { code })
  }
}

export default AuthApi
