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

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

  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({
      essayID,
      title,
      text,
    }: {
      essayID: string;
      title: string;
      text: string;
    }) => {
      await wwwAPI.put(
        `/essay/${essayID}`,
        {
          title,
          text,
        },
        {
          headers: {
            millis: getMillis(),
            totem,
          },
        },
      );
    },
    onSuccess: async (data, { essayID }) => {
      await queryClient.invalidateQueries({ queryKey: ["forum"] });
      await queryClient.invalidateQueries({ queryKey: ["essay"] });
    },
  });
}
