"use client";

import { useMutation } from "@apollo/client/react";
import { useAppDispatch } from "@/store/hooks";
import { addItem } from "@/store/slices/cart-slice";
import { CREATE_MERGE_CART } from "@/graphql";
import { GUEST_CART_ID } from "@/utils/constants";
import { setCookie } from "@utils/cookie-tools";
import { formatCartDetail } from "@/utils/cartDetailTools";

export function useMergeCart() {
  const dispatch = useAppDispatch();

  const [mergeCart, { loading: isLoading }] = useMutation(CREATE_MERGE_CART, {
    onCompleted: (response) => {
      const responseData = response?.createMergeCart?.mergeCart;
      if (!responseData) {
        return;
      }
       const cartId = responseData?.id ?? null;

      if (cartId !== null && typeof cartId !== "undefined") {
        setCookie(GUEST_CART_ID, String(cartId));
      }
      const cartDetail = formatCartDetail(responseData);

      dispatch(addItem(cartDetail));
    },
    onError: (_error) => {
    },
  });

  return {
    mergeCart,
    isLoading,
  };
}
