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 usePutAutoEssay() {
  const { t } = useTranslation();

  const { autoEssayID } = useForumStore();

  const { totem } = useAvatarStore();

  const queryClient = useQueryClient();

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