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 { useAvatarStore } from "src/Stores";
import { sprintf } from "sprintf-js";

export default function usePostGetTotem() {
  const { setSession, saveTotem } = useAvatarStore();

  const { t } = useTranslation();

  return useMutation({
    mutationFn: async ({
      avatarID,
      avatarCipher,
    }: {
      avatarID: string;
      avatarCipher: string;
    }) => {
      const { data } = await wwwAXIOS.post(
        "/avatar/getTotem",
        {
          avatarID,
          avatarCipher,
        },
        {
          headers: {
            millis: getMillis(),
          },
        },
      );
      return data;
    },
    onSuccess: async (data) => {
      setSession(data);
      saveTotem();
      toast.success(sprintf(t("signedInText"), data.avatarName));
    },
    onError: () => {
      toast.warning(t("wrongAvatar"));
    },
  });
}
