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

export default function usePutAutoEssay() {
  const { totem } = useTaehuiStore();

  const t = useTranslations();

  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({
      autoEssayID,
      title,
      text,
    }: {
      autoEssayID: number;
      title: string;
      text: string;
    }) => {
      await wwwAPI.put(
        `/autoEssay/${autoEssayID}`,
        {
          title,
          text,
        },
        {
          headers: {
            millis: getMillis(),
            totem,
          },
        },
      );
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ["autoEssay"] });
      toast.success(t("postedAutoEssay"));
    },
  });
}
