import { useTaehuiStore } from "@/state/Stores";
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 usePostGetTotem() {
  const { setSession, saveTotem } = useTaehuiStore();

  const t = useTranslations();

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