"use client";

/** دریافت قیمت‌گذاری سبد از سرور هر بار که سبد یا گزینه‌های تسویه تغییر کند */
import { useEffect, useState } from "react";
import type { CartPricing } from "@/server/services/cart";
import type { CartLine } from "./store";

export function usePricing(lines: CartLine[], opts: { discountCode?: string; shippingMethodId?: string; province?: string } = {}) {
  const [data, setData] = useState<CartPricing | null>(null);
  const [loading, setLoading] = useState(true);
  const key = JSON.stringify({ lines: lines.map(({ variantId, qty }) => ({ variantId, qty })), ...opts });

  useEffect(() => {
    const ctrl = new AbortController();
    setLoading(true);
    fetch("/api/cart/preview", { method: "POST", headers: { "Content-Type": "application/json" }, body: key, signal: ctrl.signal })
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => d && setData(d))
      .catch(() => {})
      .finally(() => !ctrl.signal.aborted && setLoading(false));
    return () => ctrl.abort();
  }, [key]);

  return { data, loading };
}
