"use client";

/**
 * Auth-state listener: on transition from signed-out to signed-in, merges guest
 * cart into user cart via Convex carts.merge, then clears the guest session cookie.
 * Place inside ClerkProvider + ConvexClientProvider (e.g. root layout).
 *
 * Merge runs exactly once per sign-in. On merge failure (e.g. network), the
 * guest cookie is left in place so the guest cart remains available; the user
 * can retry by refreshing or signing in again.
 *
 * See docs/session-implementation-plan.md Phase 4.
 */

import { useConvexAuth, useMutation } from "convex/react";
import { useEffect, useRef } from "react";
import { api } from "../../../../../convex/_generated/api";
import { clearGuestSessionCookie, getGuestSessionId } from "./cookie";

export function SessionCartMerge() {
  const { isLoading, isAuthenticated } = useConvexAuth();
  const mergeCart = useMutation(api.carts.merge);
  const previousSignedInRef = useRef<boolean | null>(null);

  useEffect(() => {
    if (isLoading) return;

    const wasSignedIn = previousSignedInRef.current;
    previousSignedInRef.current = isAuthenticated;

    if (wasSignedIn === null || wasSignedIn === true || !isAuthenticated) return;

    const sessionId = getGuestSessionId();

    if (sessionId) {
      mergeCart({ sessionId })
        .then(() => {
          clearGuestSessionCookie();
        })
        .catch(() => {
          // On failure, do not clear the cookie so guest cart remains available.
          // User can retry by refreshing or signing in again.
        });
    } else {
      // No guest cart to merge; clear any stale cookie so we don't use old ID.
      clearGuestSessionCookie();
    }
  }, [isLoading, isAuthenticated, mergeCart]);

  return null;
}
