import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as api from "../service/TaskCommentService";
import { CreateTaskCommentType, UpdateTaskCommentType } from "../types/TaskCommentTypes";

export const useGetTaskComments = (taskId: string, enabled = true) => {
  return useQuery({
    queryKey: ["task-comments", taskId],
    queryFn: () => api.getTaskComments(taskId),
    enabled: !!taskId && enabled,
  });
};

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

  return useMutation({
    mutationFn: (variables: CreateTaskCommentType) => api.createTaskComment(variables),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["task-comments", variables.taskId] });
    },
  });
};

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

  return useMutation({
    mutationFn: ({ id, params }: { id: string; params: UpdateTaskCommentType; taskId: string }) =>
      api.updateTaskComment(id, params),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["task-comments", variables.taskId] });
    },
  });
};

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

  return useMutation({
    mutationFn: ({ id }: { id: string; taskId: string }) => api.deleteTaskComment(id),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["task-comments", variables.taskId] });
    },
  });
};
