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 usePostAutoEssay() {
  const { totem } = useTaehuiStore();

  const t = useTranslations();

  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({
      forumID,
      title,
      text,
    }: {
      forumID: string;
      title: string;
      text: string;
    }) => {
      const {
        data: { autoEssayID },
      } = await wwwAPI.post(
        `/autoEssay/${forumID}`,
        {
          title,
          text,
        },
        {
          headers: {
            millis: getMillis(),
            totem,
          },
        },
      );

      return autoEssayID;
    },
    onSuccess: async (data) => {
      await queryClient.invalidateQueries({ queryKey: ["autoEssay"] });
      toast.success(t("postedAutoEssay"));
    },
  });
}
