import api from '../utils/request'

export interface AdminApiKey {
  id: number
  name: string
  description?: string | null
  key_prefix: string
  scopes: string
  is_active: boolean
  is_revoked: boolean
  created_by: number
  creator_mobile?: string | null
  last_used_at?: string | null
  last_used_ip?: string | null
  use_count: number
  created_at: string
  updated_at: string
}

export interface AdminApiKeySecretDisplay extends AdminApiKey {
  key_once: string
}

export interface AdminApiKeyList {
  total: number
  items: AdminApiKey[]
}

export interface AdminApiKeyCreatePayload {
  name: string
  description?: string
  scopes?: string
  admin_password: string
  sms_code: string
}

export interface AdminApiKeyUpdatePayload {
  name?: string
  description?: string
  scopes?: string
}

export interface AdminApiKeyRevokePayload {
  admin_password: string
  sms_code: string
}

export interface ListAdminApiKeysParams {
  skip?: number
  limit?: number
  keyword?: string
  status?: 'active' | 'disabled' | 'revoked'
}

export const listAdminApiKeys = (params?: ListAdminApiKeysParams) => {
  return api.get<AdminApiKeyList>('/admin-api-keys/', { params })
}

export const getAdminApiKey = (id: number) => {
  return api.get<AdminApiKey>(`/admin-api-keys/${id}`)
}

export const createAdminApiKey = (data: AdminApiKeyCreatePayload) => {
  return api.post<AdminApiKeySecretDisplay>('/admin-api-keys/', data)
}

export const updateAdminApiKey = (id: number, data: AdminApiKeyUpdatePayload) => {
  return api.put<AdminApiKey>(`/admin-api-keys/${id}`, data)
}

export const disableAdminApiKey = (id: number) => {
  return api.post<AdminApiKey>(`/admin-api-keys/${id}/disable`)
}

export const enableAdminApiKey = (id: number) => {
  return api.post<AdminApiKey>(`/admin-api-keys/${id}/enable`)
}

export const revokeAdminApiKey = (id: number, data: AdminApiKeyRevokePayload) => {
  return api.post<AdminApiKey>(`/admin-api-keys/${id}/revoke`, data)
}

export const sendAdminApiKeySms = () => {
  return api.post('/admin-api-keys/send-verification-code')
}
