export interface ApiSessionResult {
  authenticated: boolean;
  error?: string;
}

export function apiHeaders(apiAccessKey: string) {
  const headers: Record<string, string> = { "content-type": "application/json" };
  if (apiAccessKey) {
    headers["x-api-key"] = apiAccessKey;
  }
  return headers;
}

export function apiFetch(input: RequestInfo | URL, init: RequestInit = {}) {
  return fetch(input, {
    ...init,
    credentials: init.credentials ?? "same-origin",
  });
}

export async function getApiSession(): Promise<ApiSessionResult> {
  const response = await apiFetch("/api/auth/session");
  return readSessionResponse(response);
}

export async function loginApiSession(
  apiAccessKey: string,
): Promise<ApiSessionResult> {
  const response = await apiFetch("/api/auth/session", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ api_access_key: apiAccessKey }),
  });
  return readSessionResponse(response);
}

export async function logoutApiSession(): Promise<ApiSessionResult> {
  const response = await apiFetch("/api/auth/session", {
    method: "DELETE",
  });
  return readSessionResponse(response);
}

async function readSessionResponse(response: Response): Promise<ApiSessionResult> {
  const body = (await response.json().catch(() => ({}))) as {
    authenticated?: unknown;
    error?: unknown;
  };
  return {
    authenticated: response.ok && body.authenticated === true,
    error: typeof body.error === "string" ? body.error : undefined,
  };
}
