const CSRF_COOKIE_NAME = "bh-csrf-token";

function getCsrfToken(): string {
  const match = document.cookie
    .split("; ")
    .find((c) => c.startsWith(`${CSRF_COOKIE_NAME}=`));
  return match ? match.split("=")[1] : "";
}

/** Wrapper around fetch that auto-includes the CSRF token header for admin API calls */
export function adminFetch(url: string, init?: RequestInit): Promise<Response> {
  const headers = new Headers(init?.headers);
  if (!headers.has("x-csrf-token")) {
    headers.set("x-csrf-token", getCsrfToken());
  }
  return fetch(url, { ...init, headers });
}
