import { parseMhCookieRaw } from '@/lib/mh-cookie';

/**
 * Read the CSRF token to send in the `x-csrf-token` header.
 *
 * Primary:  explicit `csrf_token` cookie (double-submit pattern).
 * Fallback: HMAC token embedded in the `mh` hint cookie (.t field).
 *           The server computes the same HMAC when the csrf_token cookie is
 *           absent, so both sides agree without a round-trip.
 */
export function getCsrfToken(): string {
  const csrfCookie = document.cookie
    .split('; ')
    .find((c) => c.startsWith('csrf_token='))
    ?.split('=')[1];
  if (csrfCookie) return csrfCookie;

  // Fallback: extract from the mh hint cookie (.t field).
  const raw = document.cookie.match(/(?:^|;\s*)mh=([^;]+)/)?.[1] ?? '';
  const p = parseMhCookieRaw(raw);
  if (p?.t) return p.t;
  return '';
}
