"use client";

/**
 * Single source of truth for cart/guest identity.
 * Use this hook to get sessionId for Convex cart queries/mutations when isGuest is true.
 * See docs/session-implementation-plan.md Phase 3.
 */

import { useConvexAuth } from "convex/react";
import type { CartSession } from "./types";
import {
  getGuestSessionId,
  setGuestSessionCookie,
  generateGuestSessionId,
} from "./cookie";

/**
 * Returns the current cart session: either guest (with sessionId) or authenticated (no sessionId).
 *
 * - **Signed in:** `{ sessionId: undefined, isGuest: false }` — use Convex auth; do not pass sessionId.
 * - **Signed out:** `{ sessionId: string, isGuest: true }` — pass sessionId to cart queries/mutations.
 *
 * While Convex auth is still loading, we treat the user as guest and resolve sessionId from
 * cookie (or set it client-side if missing). This keeps guest cart working from first paint;
 * once auth loads and the user is authenticated, the return value switches to authenticated.
 * Cart callers do not need to wait for auth to load.
 *
 * No Convex calls are made inside this hook.
 */
export function useCartSession(): CartSession {
  const { isLoading, isAuthenticated } = useConvexAuth();

  if (!isLoading && isAuthenticated) {
    return { sessionId: undefined, isGuest: false };
  }

  // Guest path (including while auth is still loading): use cookie or fallback.
  let sessionId = getGuestSessionId();
  if (sessionId === null) {
    sessionId = generateGuestSessionId();
    setGuestSessionCookie(sessionId);
  }
  return { sessionId, isGuest: true };
}
