import { toast } from "sonner";
import { InferRequestType, InferResponseType } from "hono";
import { useMutation, useQueryClient } from "@tanstack/react-query";

import { client } from "@/lib/rpc";

type ResponseType = InferResponseType<
  (typeof client.api.tasks)[":taskId"]["comments"][":commentId"]["$delete"],
  200
>;
type RequestType = InferRequestType<
  (typeof client.api.tasks)[":taskId"]["comments"][":commentId"]["$delete"]
>;

export const useDeleteComment = () => {
  const queryClient = useQueryClient();

  const mutation = useMutation<ResponseType, Error, RequestType>({
    mutationFn: async ({ param }) => {
      const response = await client.api.tasks[":taskId"]["comments"][":commentId"]["$delete"]({
        param,
      });

      if (!response.ok) {
        throw new Error("Something went wrong");
      }

      return await response.json();
    },
    onSuccess: ({ data }, { param }) => {
      toast.success("Comment deleted");
      queryClient.invalidateQueries({ queryKey: ["comments", param.taskId] });
    },
    onError: () => {
      toast.error("Failed to delete comment");
    },
  });

  return mutation;
}; 