import { isClientFault, 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 usePutCommentary() {
  const queryClient = useQueryClient();

  const t = useTranslations();

  return useMutation({
    mutationFn: async ({
      commentaryID,
      avatarCipher,
      text,
    }: {
      commentaryID: number;
      avatarCipher: string;
      text: string;
    }) => {
      await wwwAPI.put(
        "/commentary",
        {
          commentaryID,
          avatarCipher,
          text,
        },
        {
          headers: {
            millis: getMillis(),
          },
        },
      );
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ["commentary"] });
    },
    onError: (e) => {
      if (isClientFault(e)) {
        toast.error(t("failedValidateCipher"));
      }
    },
  });
}
