import type { AdminConfig, ApplyResult, ConnectedAccountStatus, LocalStatusResult, ModelOptionsResult, PoolKeysResult, ProviderTestResult, UsageResult, ValidationResult, } from "./types" export class ApiError extends Error {} async function api(path: string, options: RequestInit = {}): Promise { const response = await fetch(path, { headers: { "Content-Type": "application/json", ...(options.headers || {}) }, ...options, cache: "no-store", }) if (!response.ok) { let detail = "" try { const payload = await response.json() detail = typeof payload.detail === "string" ? payload.detail : "" } catch { // The status remains useful when an upstream proxy returns a non-JSON page. } throw new ApiError(detail || `${response.status} ${response.statusText}`) } return response.json() as Promise } export function fetchAdminConfig(): Promise { return api("/admin/api/config") } export function validateConfig(values: Record): Promise { return api("/admin/api/config/validate", { method: "POST", body: JSON.stringify({ values }), }) } export function applyConfig(values: Record): Promise { return api("/admin/api/config/apply", { method: "POST", body: JSON.stringify({ values }), }) } export async function fetchLocalStatus(): Promise { return api("/admin/api/providers/local-status") } export function testProvider(providerId: string): Promise { return api(`/admin/api/providers/${providerId}/test`, { method: "POST", body: "{}", }) } export function fetchConnectedAccount(providerId: string): Promise { return api(`/admin/api/providers/${providerId}/auth`) } export function startConnectedAccountLogin( providerId: string, mode: "browser" | "device", ): Promise { return api(`/admin/api/providers/${providerId}/auth/login`, { method: "POST", body: JSON.stringify({ mode }), }) } export function cancelConnectedAccountLogin(providerId: string): Promise { return api(`/admin/api/providers/${providerId}/auth/cancel`, { method: "POST", }) } export function disconnectConnectedAccount(providerId: string): Promise { return api(`/admin/api/providers/${providerId}/auth`, { method: "DELETE", }) } export function fetchModelOptions(refresh = false): Promise { const path = refresh ? "/admin/api/models/refresh" : "/admin/api/models" return api(path, { method: refresh ? "POST" : "GET" }) } export function fetchPoolKeys(fieldKey: string): Promise { return api(`/admin/api/pools/${encodeURIComponent(fieldKey)}`) } export function fetchUsageStats(): Promise { return api("/admin/api/usage") }