/**
 * 真实认证服务
 * 用于连接后端 /api/auth 接口
 */

const baseUrl = import.meta.env.VITE_MOSQUITO_API_BASE_URL ?? ''

interface LoginRequest {
  username: string
  password: string
}

interface LoginResponse {
  token: string
  tokenType: string
  expiresIn: number
  userId: string
  username: string
  displayName: string
  roles: string[]
  permissions: string[]
}

interface UserInfo {
  id: string
  username: string
  displayName: string
  roles: string[]
  permissions: string[]
}

interface ApiResponse<T> {
  code: number
  message?: string
  data: T
}

export const authApi = {
  /**
   * 用户名密码登录
   */
  async login(username: string, password: string): Promise<LoginResponse | null> {
    try {
      const response = await fetch(`${baseUrl}/api/auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password } as LoginRequest)
      })

      const payload: ApiResponse<LoginResponse> = await response.json()

      // 后端成功返回 code=200
      if (payload.code === 200 || response.ok) {
        return payload.data
      }

      throw new Error(payload.message || '登录失败')
    } catch (error) {
      console.error('Login failed:', error)
      return null
    }
  },

  /**
   * 验证Token
   */
  async verifyToken(token: string): Promise<boolean> {
    try {
      const response = await fetch(`${baseUrl}/api/auth/verify`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      const payload: ApiResponse<unknown> = await response.json()
      // 后端成功返回 code=200，无效token返回 code=401
      return payload.code === 200
    } catch {
      return false
    }
  },

  /**
   * 获取当前用户信息
   */
  async getCurrentUser(token: string): Promise<UserInfo | null> {
    try {
      const response = await fetch(`${baseUrl}/api/auth/me`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      const payload: ApiResponse<UserInfo> = await response.json()

      // 后端成功返回 code=200
      if (payload.code === 200 || response.ok) {
        return payload.data
      }

      return null
    } catch {
      return null
    }
  },

  /**
   * 登出
   */
  async logout(token: string): Promise<boolean> {
    try {
      await fetch(`${baseUrl}/api/auth/logout`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      return true
    } catch {
      return false
    }
  }
}
