// api.ts から分割（挙動不変）: AAO Gateway（virtual key 管理 + サーバ状態）。

// ── AAO Gateway: virtual key admin (Phase 2a + 2b) ──────────────────────
//
// Talks to /api/admin/gateway/keys/* — requires admin role. The raw
// bearer key is returned ONCE from POST / and POST /:id/rotate; UI must
// surface it to the user immediately and not expose it again.

export interface GatewayKey {
  id: string;
  object: 'gateway.key';
  keyPrefix: string;
  team: string;
  allowedModels: string[] | null;
  source: 'admin' | 'config-import';
  createdAt: string;
  createdBy: string | null;
  revokedAt: string | null;
  revokedBy: string | null;
  lastUsedAt: string | null;
  tokensBudget: number | null;
  rateLimitRpm: number | null;
  /** Only present on POST / rotate responses. */
  key?: string;
}

export interface GatewayKeyUsageResponse {
  keyId: string;
  currentPeriod: string;
  tokensIn: number;
  tokensOut: number;
  tokensTotal: number;
  tokensBudget: number | null;
  remaining: number | null;
  requestsThisMonth: number;
  rateLimitRpm: number | null;
  // Phase 3a F9: `rateRecentRequests` removed. The field was always
  // null because the admin process doesn't own the gateway's live
  // RateLimiter. Phase 3b/3c may re-add it via gateway IPC.
  history: Array<{ period: string; tokensIn: number; tokensOut: number; requests: number }>;
}

export async function listGatewayKeys(params?: { team?: string; activeOnly?: boolean }): Promise<GatewayKey[]> {
  const q = new URLSearchParams();
  if (params?.team) q.set('team', params.team);
  if (params?.activeOnly) q.set('activeOnly', 'true');
  const qs = q.toString();
  const res = await fetch(`/api/admin/gateway/keys${qs ? `?${qs}` : ''}`);
  if (!res.ok) throw new Error(`Failed to list gateway keys: ${res.status}`);
  return (await res.json()).keys;
}

export async function createGatewayKey(input: {
  team: string;
  allowedModels?: string[];
  tokensBudget?: number | null;
  rateLimitRpm?: number | null;
}): Promise<GatewayKey> {
  const res = await fetch(`/api/admin/gateway/keys`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(input),
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Failed to create gateway key (${res.status}): ${text}`);
  }
  return res.json();
}

export async function getGatewayKey(id: string): Promise<GatewayKey> {
  const res = await fetch(`/api/admin/gateway/keys/${encodeURIComponent(id)}`);
  if (!res.ok) throw new Error(`Failed to get gateway key: ${res.status}`);
  return res.json();
}

export async function patchGatewayKey(
  id: string,
  patch: {
    tokensBudget?: number | null;
    rateLimitRpm?: number | null;
    allowedModels?: string[] | null;
  },
): Promise<GatewayKey> {
  const res = await fetch(`/api/admin/gateway/keys/${encodeURIComponent(id)}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(patch),
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Failed to update gateway key (${res.status}): ${text}`);
  }
  return res.json();
}

export async function revokeGatewayKey(id: string): Promise<void> {
  const res = await fetch(`/api/admin/gateway/keys/${encodeURIComponent(id)}/revoke`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({}),
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Failed to revoke gateway key (${res.status}): ${text}`);
  }
}

export async function rotateGatewayKey(id: string): Promise<GatewayKey> {
  const res = await fetch(`/api/admin/gateway/keys/${encodeURIComponent(id)}/rotate`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({}),
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Failed to rotate gateway key (${res.status}): ${text}`);
  }
  return res.json();
}

export async function deleteGatewayKey(id: string): Promise<void> {
  const res = await fetch(`/api/admin/gateway/keys/${encodeURIComponent(id)}`, { method: 'DELETE' });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Failed to delete gateway key (${res.status}): ${text}`);
  }
}

export async function getGatewayKeyUsage(id: string): Promise<GatewayKeyUsageResponse> {
  const res = await fetch(`/api/admin/gateway/keys/${encodeURIComponent(id)}/usage`);
  if (!res.ok) throw new Error(`Failed to get gateway key usage: ${res.status}`);
  return res.json();
}

// ============================================================
// Gateway Server status (Phase 3c) — read-only admin endpoint.
// Drives the Settings → Gateway Server badge and error list.
// ============================================================
export type GatewayServerState =
  | 'unavailable'
  | 'disabled'
  | 'starting'
  | 'running'
  | 'stopping'
  | 'misconfigured';

export interface GatewayServerStatus {
  state: GatewayServerState;
  /** Desired-enabled flag read from current config. Null when no ConfigManager. */
  enabled: boolean | null;
  /** Validation errors that prevented the gateway from starting. */
  errors: string[];
  mounted: boolean;
  sharedPort: number;
  /** Only present when state==='unavailable'. */
  message?: string;
}

export async function getGatewayServerStatus(): Promise<GatewayServerStatus> {
  const res = await fetch('/api/admin/gateway/status');
  if (!res.ok) throw new Error(`Failed to get gateway status: ${res.status}`);
  return res.json();
}
