export interface ApiKey {
  id: string;
  restaurantId: string;
  name: string;
  keyPreview: string;
  key?: string;
  permissions: string[];
  callsThisMonth: number;
  status: 'active' | 'revoked';
  lastUsedAt?: string;
  createdAt: string;
}

export interface ApiKeyListResponse {
  keys: ApiKey[];
}

function normalize(row: Record<string, unknown>): ApiKey {
  const rawPerms = (row.permissions ?? []) as string[] | string;
  const permissions = typeof rawPerms === 'string'
    ? (() => { try { return JSON.parse(rawPerms); } catch { return []; } })()
    : rawPerms;
  return {
    id: row.id as string,
    restaurantId: (row.restaurantId ?? row.restaurant_id) as string,
    name: row.name as string,
    keyPreview: (row.keyPreview ?? row.key_preview) as string,
    key: row.key as string | undefined,
    permissions: Array.isArray(permissions) ? permissions : [],
    callsThisMonth: Number((row.callsThisMonth ?? row.calls_this_month) ?? 0),
    status: row.status as 'active' | 'revoked',
    lastUsedAt: (row.lastUsedAt ?? row.last_used_at) as string | undefined,
    createdAt: (row.createdAt ?? row.created_at) as 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 listApiKeys(): Promise<ApiKeyListResponse> {
  const data = await apiFetch<{ keys: Record<string, unknown>[] }>('/api/api-keys');
  return { keys: data.keys.map(normalize) };
}

export async function createApiKey(body: Record<string, unknown>): Promise<{ key: ApiKey }> {
  const data = await apiFetch<{ key: Record<string, unknown> }>('/api/api-keys', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  return { key: normalize(data.key) };
}

export async function revokeApiKey(id: string): Promise<{ key: ApiKey }> {
  const data = await apiFetch<{ key: Record<string, unknown> }>(`/api/api-keys/${id}`, { method: 'DELETE' });
  return { key: normalize(data.key) };
}
