import usePostGetTotem from "@/query/usePostGetTotem";
import { isClientFault, wwwAPI } from "@/utilities/wwwAPI";
import { useMutation } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { toast } from "react-toastify";
import { getMillis } from "taehui-lib/date";

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

  const { mutateAsync: postGetTotem } = usePostGetTotem();

  return useMutation({
    mutationFn: async ({
      avatarID,
      avatarName,
      avatarCipher,
      fax,
    }: {
      avatarID: string;
      avatarName: string;
      avatarCipher: string;
      fax: string;
    }) => {
      await wwwAPI.post(
        "/avatar",
        {
          avatarID,
          avatarCipher,
          avatarName,
          fax,
        },
        {
          headers: {
            millis: getMillis(),
          },
        },
      );
    },
    onSuccess: async (data, { avatarID, avatarCipher }) => {
      await postGetTotem({ avatarID, avatarCipher });
    },
    onError: (e) => {
      if (isClientFault(e)) {
        toast.error(t("alreadyAvatarID"));
      }
    },
  });
}
