"use client";

import { useQuery } from "convex/react";
import { useMemo } from "react";
import { api } from "../../../../../convex/_generated/api";
import type { CheckoutValidationResult } from "./types";

/**
 * Wraps `api.checkout.validateCart` for the checkout page.
 *
 * - Guest: pass sessionId from useCartSessionId().
 * - Authenticated: pass undefined; Convex resolves the signed-in user.
 *
 * The query is reactive — if the cart changes in another tab the result
 * updates automatically via Convex subscriptions.
 */
export function useCartValidation(sessionId: string | undefined): {
  result: CheckoutValidationResult | null;
  isLoading: boolean;
  error: Error | null;
} {
  const data = useQuery(api.checkout.validateCart, {
    sessionId: sessionId ?? undefined,
  });

  return useMemo(() => {
    if (data === undefined) {
      return { result: null, isLoading: true, error: null };
    }

    return {
      result: data as CheckoutValidationResult,
      isLoading: false,
      error: null,
    };
  }, [data]);
}
