"use client";

/**
 * Cart data hook: Convex carts.get with session/auth identity.
 * Returns cart, enriched items, loading, error, and computed subtotal.
 * Use for cart page, drawer, and sheet so they share one source of truth.
 *
 * - Guest: pass sessionId from useCartSessionId().
 * - Authenticated: pass undefined; Convex uses signed-in user.
 */
import { useQuery } from "convex/react";
import { useMemo } from "react";
import { api } from "../../../../../convex/_generated/api";
import type { CartEnrichedItem } from "./types";

function computeSubtotal(items: CartEnrichedItem[]): number {
  return items.reduce(
    (sum, item) => sum + item.priceSnapshot * item.quantity,
    0,
  );
}

export function useCart(sessionId: string | undefined) {
  const cart = useQuery(api.carts.get, { sessionId: sessionId ?? undefined });

  const result = useMemo(() => {
    if (cart === undefined) {
      return {
        cart: null,
        items: [],
        subtotal: 0,
        isLoading: true,
        error: null,
      };
    }
    if (cart === null) {
      return {
        cart: null,
        items: [],
        subtotal: 0,
        isLoading: false,
        error: null,
      };
    }
    const items = (cart.items ?? []) as CartEnrichedItem[];
    const subtotal = computeSubtotal(items);
    return {
      cart: { id: cart._id, items, subtotal },
      items,
      subtotal,
      isLoading: false,
      error: null,
    };
  }, [cart]);

  return result;
}
