import { useTaehuiStore } from "@/state/Stores";
import { isClientFault, wwwAPI } from "@/utilities/wwwAPI";
import { useMutation } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { toast } from "react-toastify";
import Swal from "sweetalert2";
import { getMillis } from "taehui-lib/date";

export default function usePutAvatar() {
  const t = useTranslations();

  const { totem, setSession, wipeSession, saveTotem } = useTaehuiStore();

  const { push } = useRouter();

  return useMutation({
    mutationFn: async ({
      avatarCipher,
      avatarCipherModified,
      avatarName,
      fax,
      avatarIntro,
    }: {
      avatarCipher: string;
      avatarCipherModified: string;
      avatarName: string;
      fax: string;
      avatarIntro: string;
    }) => {
      const { data } = await wwwAPI.put(
        "/avatar",
        {
          avatarCipher,
          avatarCipherModified,
          avatarName,
          fax,
          avatarIntro,
        },
        {
          headers: {
            millis: getMillis(),
            totem,
          },
        },
      );
      return data;
    },
    onSuccess: async (
      { isAvatarCipherModified },
      { avatarName, fax, avatarIntro },
    ) => {
      if (isAvatarCipherModified) {
        wipeSession();
        await Swal.fire("Taehui", t("doModifiedAvatar"), "success");
      } else {
        setSession({
          avatarName,
          fax,
          avatarIntro,
        });
      }
      saveTotem();
      push("/");
    },
    onError: (e) => {
      if (isClientFault(e)) {
        toast.error(t("failedValidateCipher"));
      }
    },
  });
}
