'use client';

import { memo, useEffect } from 'react';
import { useAppDispatch } from '@akinon/next/redux/hooks';
import { useAddProductMutation } from '../data/client/product';
import { basketApi } from '@akinon/next/data/client/basket';
import { useGetBasketQuery } from '@akinon/next/data/client/basket';

export const LiveCommerce = memo(function Callback() {
  const dispatch = useAppDispatch();
  const { refetch: refetchBasketData } = useGetBasketQuery();
  const [addProduct] = useAddProductMutation();

  useEffect(() => {
    document.addEventListener('refresh-basket', () => refetchBasketData());

    document.addEventListener('add-to-cart', async (e: CustomEvent) => {
      const productData = e.detail.data;

      await addProduct({
        product: productData.product,
        quantity: productData.quantity,
        attributes: productData.attributes
      })
        .unwrap()
        .then((data) =>
          dispatch(
            basketApi.util.updateQueryData(
              'getBasket',
              undefined,
              (draftBasket) => {
                Object.assign(draftBasket, data.basket);
              }
            )
          )
        );
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return null;
});
