import { useSafeQuery } from '@/hooks/use-safe-query';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import {
  createTrainingAction,
  deleteTrainingAction,
  getTrainingAction,
  getTrainingByIdAction,
  updateTrainingAction,
} from '../actions/training-actions';
import { TrainingSchema } from '../schemas/training';

export function useTrainingQuery(params = {}) {
  return useSafeQuery(['training', params], () => getTrainingAction(params));
}

export function useTrainingByIdQuery(id: number) {
  return useSafeQuery(['training', id], () => getTrainingByIdAction(id));
}

export function useCreateTraining() {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: (data: TrainingSchema) => createTrainingAction(data),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['training'] }),
  });
  return mutation;
}

export function useUpdateTraining() {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: (data: TrainingSchema) => updateTrainingAction(data),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['training'] }),
  });
  return mutation;
}

export function useDeleteTraining() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => deleteTrainingAction(id),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['training'] }),
  });
}
