import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as api from "../service/ScheduleService";
import type { CreateScheduleType } from "../types/Types";

export const useGetSchedules = (params?: Record<string, unknown>) => {
  return useQuery({
    queryKey: ["schedules", params],
    queryFn: () => api.getSchedules(params),
  });
};

export const useDeleteSchedule = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.deleteSchedule,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["schedules"] });
    },
  });
};

export const useCreateSchedule = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.createSchedule,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["schedules"] });
    },
  });
};

export const useUpdateSchedule = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, params }: { id: string; params: CreateScheduleType }) =>
      api.updateSchedule(id, params),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: ["schedules"] });
      queryClient.invalidateQueries({ queryKey: ["schedules", id] });
    },
  });
};

export const useGetSchedule = (id: string) => {
  return useQuery({
    queryKey: ["schedule", id],
    queryFn: () => api.getSchedule(id),
  });
};
