/**
 * Client-only guest session cookie utilities.
 * Use from hooks/components only; do not import in middleware or server components.
 * See docs/session-implementation-plan.md.
 */

import {
  GUEST_SESSION_COOKIE_NAME,
  GUEST_SESSION_MAX_AGE_SECONDS,
} from "./constants";

/**
 * Reads the guest session ID from document.cookie. Returns null when not in the
 * browser or when the cookie is missing.
 */
export function getGuestSessionId(): string | null {
  if (typeof document === "undefined") return null;
  const cookies = document.cookie.split(";");
  for (const part of cookies) {
    const eq = part.indexOf("=");
    if (eq === -1) continue;
    const name = part.slice(0, eq).trim();
    if (name === GUEST_SESSION_COOKIE_NAME) {
      const value = part.slice(eq + 1).trim();
      if (!value) return null;
      try {
        return decodeURIComponent(value);
      } catch {
        return value;
      }
    }
  }
  return null;
}

/**
 * Sets the guest session cookie in the browser. Use for client-side fallback
 * when the cookie is missing (e.g. client-only nav).
 */
export function setGuestSessionCookie(sessionId: string): void {
  if (typeof document === "undefined") return;
  const secure =
    typeof window !== "undefined" && window.location?.protocol === "https:";
  const parts = [
    `${GUEST_SESSION_COOKIE_NAME}=${encodeURIComponent(sessionId)}`,
    "Path=/",
    `max-age=${GUEST_SESSION_MAX_AGE_SECONDS}`,
    "SameSite=Lax",
  ];
  if (secure) parts.push("Secure");
  document.cookie = parts.join("; ");
}

/**
 * Clears the guest session cookie (e.g. after merge on login).
 */
export function clearGuestSessionCookie(): void {
  if (typeof document === "undefined") return;
  document.cookie = `${GUEST_SESSION_COOKIE_NAME}=; Path=/; max-age=0; SameSite=Lax`;
}

/**
 * Generates a new guest session ID (UUID v4). Uses crypto.randomUUID() in
 * modern browsers; no extra dependency.
 */
export function generateGuestSessionId(): string {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  }
  // Minimal fallback for very old environments
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}
