import request from '@/utils/request'
import type { ApiResult, PageResult } from '@/api'
import type { AppApiKey, AppApiKeyParam } from './model'
import { APP_API_URL } from '@/config/setting'

const BASE = APP_API_URL + '/apikey'

/** 分页查询 API Key - 直接用基础路径，后端 @GetMapping 支持分页参数 */
export async function pageAppApiKey(params: AppApiKeyParam) {
  const res = await request.get<ApiResult<PageResult<AppApiKey>>>(BASE, { params })
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 查询全部 API Key */
export async function listAppApiKey(params?: AppApiKeyParam) {
  const res = await request.get<ApiResult<AppApiKey[]>>(BASE, { params })
  if (res.data.code === 0 && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 创建 API Key */
export async function createAppApiKey(data: {
  name: string
  expireTime?: string
  scopes?: string
  remark?: string
}) {
  const res = await request.post<ApiResult<AppApiKey>>(BASE, data)
  if (res.data.code === 0) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 更新 API Key 状态 */
export async function updateAppApiKeyStatus(id: number, status: number) {
  const res = await request.put<ApiResult<unknown>>(BASE + `/${id}/status?status=${status}`)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 删除 API Key */
export async function removeAppApiKey(id: number) {
  const res = await request.delete<ApiResult<unknown>>(BASE + '/' + id)
  if (res.data.code === 0) return res.data.message
  return Promise.reject(new Error(res.data.message))
}

/** 获取 API Key 速率限制 */
export async function getApiRateLimits() {
  const res = await request.get<ApiResult<{
    plan: string
    rps: number
    dailyLimit: number
    usedToday: number
    remainingToday: number
  }>>(BASE + '/rate-limits')
  if (res.data.code === 0 && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}

/** 获取 API Key 统计 */
export async function getAppApiKeyStats() {
  const res = await request.get<ApiResult<{
    total: number
    active: number
    expired: number
    disabled: number
    totalUsage: number
  }>>(BASE + '/stats')
  if (res.data.code === 0 && res.data.data) return res.data.data
  return Promise.reject(new Error(res.data.message))
}
