import { useMutation } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "react-toastify";
import { getMillis } from "taehui-ts/date";

import { wwwAXIOS } from "src/Www";
import usePostGetTotem from "src/avatar/usePostGetTotem";

export default function usePostAvatar() {
  const { t } = useTranslation();

  const { mutate: postGetTotem } = usePostGetTotem();

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