/**
 * Client-side fetch() wrapper that adds the double-submit CSRF token.
 *
 * Reads the `sr_csrf` cookie from `document.cookie` (issued by the middleware
 * on the first page load) and echoes it back in the `x-csrf-token` header, so
 * the server's `requireCsrf` guard (see `@/lib/auth/csrf`) can prove the
 * request originated from our own page.
 *
 * NOTE: this module intentionally does NOT import `@/lib/auth/csrf` — that
 * module pulls in `next/server`, which is forbidden in client bundles. The two
 * constants are mirrored here on purpose; `tests/e2e/csrf_tokens.test.ts`
 * asserts they stay in sync with the server contract.
 *
 * Existing options pass through untouched: the method and body (JSON strings,
 * FormData, …) are preserved, and only the CSRF header is added — the browser
 * still sets the multipart boundary for FormData itself.
 */

/** Must match `CSRF_COOKIE` in `@/lib/auth/csrf`. */
export const CSRF_COOKIE = "sr_csrf";

/** Must match `CSRF_HEADER` in `@/lib/auth/csrf`. */
export const CSRF_HEADER = "x-csrf-token";

export function apiFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
  const token = readDocumentCookie(CSRF_COOKIE);
  const headers = new Headers(init?.headers);
  if (token) headers.set(CSRF_HEADER, token);
  return fetch(input, { ...init, headers });
}

/** Reads a cookie value from `document.cookie` (undefined when absent). */
function readDocumentCookie(name: string): string | undefined {
  if (typeof document === "undefined") return undefined;
  const prefix = `${name}=`;
  for (const part of document.cookie.split(";")) {
    const trimmed = part.trim();
    if (!trimmed.startsWith(prefix)) continue;
    const raw = trimmed.slice(prefix.length);
    try {
      return decodeURIComponent(raw);
    } catch {
      return raw;
    }
  }
  return undefined;
}
