/**
 * adminAuth — shared helpers for DriveHub admin authentication.
 *
 * Token is stored in TWO places so different layers can read it:
 *
 *   sessionStorage  — client-only, per-tab.  Read by the React layout guard.
 *   Cookie          — readable by both the browser and Next.js Edge middleware.
 *                     Allows server-side protection without a separate API call.
 *
 * Cookie name : drivehub_admin_session
 * SS key      : drivehub_admin_token
 *
 * Both are written on login and cleared on logout.
 * On first read in a new tab, getAdminToken() syncs the cookie back to
 * sessionStorage so subsequent reads stay fast.
 */

export const ADMIN_SS_KEY     = "drivehub_admin_token";
export const ADMIN_COOKIE_NAME = "drivehub_admin_session";

// ── Read ──────────────────────────────────────────────────────────────────────

/**
 * Returns the admin token from sessionStorage, falling back to the cookie.
 * Also syncs the cookie value back into sessionStorage for this tab.
 * Returns null if neither storage contains a token.
 */
export function getAdminToken(): string | null {
  if (typeof window === "undefined") return null;

  // 1 — sessionStorage (fastest, tab-scoped)
  const ss = sessionStorage.getItem(ADMIN_SS_KEY);
  if (ss) {
    console.log("[ADMIN_TOKEN] read from sessionStorage");
    return ss;
  }

  // 2 — Cookie fallback (cross-tab, survives browser restart)
  const match = document.cookie.match(
    new RegExp(`(?:^|;\\s*)${ADMIN_COOKIE_NAME}=([^;]+)`),
  );
  const cookieToken = match?.[1] ?? null;

  if (cookieToken) {
    console.log("[ADMIN_TOKEN] restored from cookie → synced to sessionStorage");
    sessionStorage.setItem(ADMIN_SS_KEY, cookieToken);
  }

  return cookieToken;
}

// ── Write ─────────────────────────────────────────────────────────────────────

/**
 * Persists the token to both sessionStorage and a SameSite cookie.
 * Call this immediately after a successful login API response.
 */
export function setAdminToken(token: string): void {
  if (typeof window === "undefined") return;

  console.log("[ADMIN_TOKEN] stored in sessionStorage + cookie");

  sessionStorage.setItem(ADMIN_SS_KEY, token);

  const secure = window.location.protocol === "https:" ? "; Secure" : "";
  // Max-Age = 24 h  (86400 s)
  document.cookie = [
    `${ADMIN_COOKIE_NAME}=${token}`,
    "path=/",
    "SameSite=Strict",
    "Max-Age=86400",
    secure,
  ]
    .filter(Boolean)
    .join("; ");
}

// ── Clear ─────────────────────────────────────────────────────────────────────

/**
 * Removes the token from both sessionStorage and the cookie.
 * Call this on logout.
 */
export function clearAdminToken(): void {
  if (typeof window === "undefined") return;

  console.log("[ADMIN_TOKEN] cleared from sessionStorage + cookie");

  sessionStorage.removeItem(ADMIN_SS_KEY);

  // Expire the cookie immediately
  document.cookie = [
    `${ADMIN_COOKIE_NAME}=`,
    "path=/",
    "SameSite=Strict",
    "expires=Thu, 01 Jan 1970 00:00:00 GMT",
  ].join("; ");
}
