// hooks/useCart.js
import { useMemo } from "react";
import { useGetCartQuery } from "./cartApi";

export const useCart = () => {
  const queryResult = useGetCartQuery(undefined, {
    pollingInterval: 0,
    refetchOnMountOrArgChange: false, // Cache'den kullan, gereksiz GET'i engelle
    refetchOnFocus: false,
    refetchOnReconnect: false,
  });

  const { data: response = {} } = queryResult;
  const cartData = response.data || {};

  const cartItems = useMemo(() => {
    if (!cartData || typeof cartData !== "object") return [];
    return Object.values(cartData).flat();
  }, [cartData]);

  const cartCount = useMemo(() => {
    return cartItems.reduce((total, item) => {
      const qty = parseInt(item.product_quantity, 10) || 0;
      return total + qty;
    }, 0);
  }, [cartItems]);

  const getCartItem = (productId) => {
    if (!productId) return null;
    const pid = String(productId);
    return cartItems.find(
      (item) =>
        String(item.product?.id) === pid || String(item.product_id) === pid,
    );
  };

  return {
    cartData,
    cartItems,
    cartCount,
    getCartItem,
    ...queryResult,
  };
};
