export interface ProviderKeyInfo {
  id: string;
  provider_name: string;
  display_name: string;
  description: string;
  key_hint: string;
  is_active: boolean;
  has_env_fallback: boolean;
  created_at: string;
  updated_at: string;
}

async function apiFetch<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, { credentials: 'include', ...options });
  const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
  if (!res.ok) throw new Error((json.error as string) || `Request failed: ${res.status}`);
  return json as T;
}

export async function listProviderKeys(): Promise<ProviderKeyInfo[]> {
  const data = await apiFetch<{ keys: ProviderKeyInfo[] }>('/api/settings/provider-keys');
  return data.keys;
}

export async function saveProviderKey(providerName: string, apiKey: string): Promise<ProviderKeyInfo> {
  const data = await apiFetch<{ key: ProviderKeyInfo }>('/api/settings/provider-keys', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ providerName, apiKey }),
  });
  return data.key;
}

export async function deleteProviderKey(providerName: string): Promise<void> {
  await apiFetch<{ success: boolean }>(`/api/settings/provider-keys?provider=${encodeURIComponent(providerName)}`, {
    method: 'DELETE',
  });
}
