"use client";

/**
 * Cart mutation hooks: addItem, updateItem, removeItem, clear with session/auth identity.
 * Use the same sessionId as useCart (from useCartSessionId) so guest and auth stay consistent.
 *
 * addItem returns a Promise so callers can use .then()/.catch() for loading and error state
 * (e.g. disable button while pending, show "Insufficient stock" on reject). Backend enforces
 * quantity ≥ 1 and stock; we validate quantity ≥ 1 client-side before calling.
 */
import { useMutation } from "convex/react";
import { api } from "../../../../../convex/_generated/api";
import type { Id } from "../../../../../convex/_generated/dataModel";

const MIN_ADD_QUANTITY = 1;

export function useCartMutations(sessionId: string | undefined) {
  const addItemMutation = useMutation(api.carts.addItem);
  const updateItemMutation = useMutation(api.carts.updateItem);
  const removeItemMutation = useMutation(api.carts.removeItem);
  const clearMutation = useMutation(api.carts.clear);

  function addItem(
    variantId: Id<"productVariants"> | string,
    quantity: number
  ): Promise<unknown> {
    if (quantity < MIN_ADD_QUANTITY) {
      return Promise.reject(
        new Error(`Quantity must be at least ${MIN_ADD_QUANTITY}`)
      );
    }
    return addItemMutation({
      variantId: variantId as Id<"productVariants">,
      quantity,
      sessionId: sessionId ?? undefined,
    });
  }

  function updateItem(variantId: string, quantity: number) {
    return updateItemMutation({
      variantId: variantId as Id<"productVariants">,
      quantity,
      sessionId: sessionId ?? undefined,
    });
  }

  function removeItem(variantId: string) {
    return removeItemMutation({
      variantId: variantId as Id<"productVariants">,
      sessionId: sessionId ?? undefined,
    });
  }

  function clear() {
    return clearMutation({ sessionId: sessionId ?? undefined });
  }

  return { addItem, updateItem, removeItem, clear };
}
