import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as api from "../service/TaskTimeService";

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

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

  return useMutation({
    mutationFn: (taskId: string) => api.startTimeTracking(taskId),
    onSuccess: (_data, taskId) => {
      queryClient.invalidateQueries({ queryKey: ["task-detail", taskId] });
      queryClient.invalidateQueries({ queryKey: ["task-times", taskId] });
    },
  });
};

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

  return useMutation({
    mutationFn: (taskId: string) => api.endTimeTracking(taskId),
    onSuccess: (_data, taskId) => {
      queryClient.invalidateQueries({ queryKey: ["task-detail", taskId] });
      queryClient.invalidateQueries({ queryKey: ["task-times", taskId] });
    },
  });
};
