import useAddressStore from "@/global-store/address";
import { LikeTypes } from "@/types/global";
import { useMutation } from "@tanstack/react-query";
import { likeService } from "@/services/like";
import useLikeStore from "@/global-store/like";
import { useSettings } from "@/hook/use-settings";

/** همگام‌سازی لایک سالن/مستر بعد از لاگین — cart/product حذف شده از بک‌اند */
export const useSyncServer = () => {
  const { currency, language } = useSettings();
  const country = useAddressStore((state) => state.country);
  const { list, setMany } = useLikeStore();
  const notSentList = {
    master: list.master.filter((listItem) => !listItem.sent),
    shop: list.shop.filter((listItem) => !listItem.sent),
  };

  const handleSaveMany = (type: Exclude<LikeTypes, "product">) => {
    likeService
      .getAll({
        type,
        lang: language?.locale,
        currency_id: currency?.id,
      })
      .then((res) => {
        setMany(
          type,
          res.data.map((item) => ({ itemId: item.id, sent: true }))
        );
      })
      .catch(() => undefined);
  };

  const { mutate: likeMany } = useMutation(
    ["likeMany"],
    (type: Exclude<LikeTypes, "product">) =>
      likeService.likeMany({
        types: notSentList[type].map((listItem) => ({
          type,
          type_id: listItem.itemId,
        })),
      }),
    {
      onSuccess: (_, type) => {
        handleSaveMany(type);
      },
    }
  );

  const handleSync = () => {
    if (!country) return;
    if (notSentList.master.length > 0 || notSentList.shop.length > 0) {
      if (notSentList.master.length > 0) likeMany("master");
      if (notSentList.shop.length > 0) likeMany("shop");
    } else {
      handleSaveMany("master");
      handleSaveMany("shop");
    }
  };

  return { handleSync };
};
