import type {
  LoginRequest,
  RegisterRequest,
  ChangePasswordRequest,
  ApiResponse,
  LoginResponseData,
  UserInfo,
} from '@/types/auth'
import { StorageManager } from '@/utils/storage'
import axios from 'axios'

/**
 * 认证相关API
 */
export class AuthAPI {
  /**
   * 用户登录
   */
  static async login(credentials: LoginRequest): Promise<ApiResponse<LoginResponseData>> {
    const response = await axios.post('/api/auth/login', credentials)

    // 登录成功后保存Token和用户信息
    if (response.data.code === 200) {
      const { token, accountInfo } = response.data.data
      StorageManager.saveAuthInfo(token, accountInfo)
    }

    return response.data
  }

  /**
   * 用户注册
   */
  static async register(userData: RegisterRequest): Promise<ApiResponse<UserInfo>> {
    const response = await axios.post('/api/auth/register', userData)
    return response.data
  }

  /**
   * 修改密码
   */
  static async changePassword(passwordData: ChangePasswordRequest): Promise<ApiResponse<string>> {
    const response = await axios.put('/api/auth/change-password', passwordData)
    return response.data
  }

  /**
   * 获取当前用户信息
   */
  static async getCurrentUser(): Promise<ApiResponse<string>> {
    const response = await axios.get('/api/auth/current-user')
    return response.data
  }

  /**
   * 登出
   */
  static logout(): void {
    StorageManager.clearAuthData()
    window.location.href = '/login'
  }
}
