// API Key 管理（对齐 PC /developer/apikeys，基址走 websopy-api）
import { get, post, put, del } from '@/utils/request'
import { WebsopyBaseUrl } from '@/config/app'

const BASE = '/app/apikey'

export interface AppApiKey {
  id: number
  name: string
  apiKey: string
  keyPrefix?: string
  status: number // 0正常 1禁用
  scopes?: string
  expireTime?: string
  lastUsedAt?: string
  usageCount?: number
  remark?: string
  createTime?: string
}

export async function pageAppApiKey(params: any) {
  const res = await get<any>(BASE, params, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '加载失败'))
}

export async function createAppApiKey(data: any) {
  const res = await post<any>(BASE, data, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '创建失败'))
}

export async function updateAppApiKeyStatus(id: number, status: number) {
  const res = await put<any>(`${BASE}/${id}/status?status=${status}`, {}, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.message
  return Promise.reject(new Error(res?.message || '操作失败'))
}

export async function removeAppApiKey(id: number) {
  const res = await del<any>(`${BASE}/${id}`, {}, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.message
  return Promise.reject(new Error(res?.message || '删除失败'))
}

export async function getAppApiKeyStats() {
  const res = await get<any>(`${BASE}/stats`, undefined, { baseUrl: WebsopyBaseUrl })
  if (res?.code === 0) return res.data
  return Promise.reject(new Error(res?.message || '加载失败'))
}
