import request from '@/utils/http'

export interface ProviderRecord {
  id: string
  code: string
  adapter: string
  base_url: string
  api_key_masked: string
  key_configured: boolean
  capabilities: string[]
  config: Record<string, unknown>
  enabled: boolean
  revision: number
  credential_kek_version: number
}

export interface ProviderInput {
  code: string
  adapter: string
  base_url: string
  api_key?: string
  capabilities: string[]
  config: Record<string, unknown>
  enabled: boolean
}

export interface ProviderConnectionResult {
  connected: boolean
  status_code?: number
  latency_ms: number
  message: string
}

export interface ProviderModel {
  id: string
  provider_id: string
  provider_model_id: string
  owned_by?: string
  metadata: Record<string, unknown>
  enabled: boolean
  discovered_at: string
  last_seen_at: string
}

export interface ModelSyncResult {
  discovered: number
  active: number
  disabled: number
  synced_at: string
}

export interface CredentialRotationResult {
  active_version: number
  loaded_versions: number[]
  rotated: number
  skipped: number
}

export function fetchProviders() {
  return request.get<ProviderRecord[]>({ url: '/api/v1/admin/providers' })
}

export function createProvider(data: ProviderInput) {
  return request.post<ProviderRecord>({ url: '/api/v1/admin/providers', params: data })
}

export function updateProvider(id: string, data: ProviderInput) {
  return request.put<ProviderRecord>({ url: `/api/v1/admin/providers/${id}`, params: data })
}

export function testProviderConnection(id: string) {
  return request.post<ProviderConnectionResult>({
    url: `/api/v1/admin/providers/${id}/test`
  })
}

export function fetchProviderModels(id: string) {
  return request.get<ProviderModel[]>({ url: `/api/v1/admin/providers/${id}/models` })
}

export function syncProviderModels(id: string) {
  return request.post<ModelSyncResult>({
    url: `/api/v1/admin/providers/${id}/models/sync`
  })
}

export function rotateProviderCredentials() {
  return request.post<CredentialRotationResult>({
    url: '/api/v1/admin/providers/credentials/rotate'
  })
}
