import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
	fetchSchedulerRuns,
	fetchSchedulerSamples,
	fetchSchedulerStatus,
	runSchedulerAction,
} from "../api/scheduler";

export function useSchedulerStatus(serviceId: string) {
	return useQuery({
		queryKey: ["scheduler", "status", serviceId],
		queryFn: () => fetchSchedulerStatus(serviceId),
		enabled: Boolean(serviceId),
		refetchInterval: 15_000,
	});
}

export function useSchedulerRuns(serviceId: string) {
	return useQuery({
		queryKey: ["scheduler", "runs", serviceId],
		queryFn: () => fetchSchedulerRuns(serviceId),
		enabled: Boolean(serviceId),
		refetchInterval: 15_000,
	});
}

export function useSchedulerSamples(serviceId: string, windowSeconds: number) {
	return useQuery({
		queryKey: ["scheduler", "samples", serviceId, windowSeconds],
		queryFn: () => fetchSchedulerSamples(serviceId, windowSeconds),
		enabled: Boolean(serviceId),
		refetchInterval: 15_000,
	});
}

export function useRunSchedulerAction() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: runSchedulerAction,
		onSuccess: (_result, serviceId) => {
			queryClient.invalidateQueries({
				queryKey: ["scheduler", "status", serviceId],
			});
			queryClient.invalidateQueries({
				queryKey: ["scheduler", "runs", serviceId],
			});
			queryClient.invalidateQueries({
				queryKey: ["scheduler", "samples", serviceId],
			});
		},
	});
}
