import { useMutation, useQueryClient } from "@tanstack/react-query";
import { wwwAXIOS } from "src/Www";
import { getMillis } from "taehui-ts/date";
import { useAvatarStore, useForumStore } from "src/Stores";
import { toast } from "react-toastify";
import { useTranslation } from "react-i18next";

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

  const { setAutoEssayID } = useForumStore();

  const { totem } = useAvatarStore();

  const queryClient = useQueryClient();

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

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