import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
	createServiceInstance,
	deleteServiceInstance,
	fetchServiceInstances,
	fetchServiceTypes,
	updateServiceInstance,
} from "../api/services";
import type { ServiceInstanceInput } from "../types";

export function useServiceTypes() {
	return useQuery({
		queryKey: ["services", "types"],
		queryFn: fetchServiceTypes,
		staleTime: 5 * 60 * 1000,
	});
}

export function useServiceInstances(serviceType?: string) {
	return useQuery({
		queryKey: ["services", "instances", serviceType ?? "all"],
		queryFn: () => fetchServiceInstances(serviceType),
		refetchInterval: 60_000,
	});
}

export function useSaveServiceInstance() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (input: ServiceInstanceInput) =>
			input.id ? updateServiceInstance(input) : createServiceInstance(input),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["services", "instances"] });
		},
	});
}

export function useDeleteServiceInstance() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (serviceId: string) => deleteServiceInstance(serviceId),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["services", "instances"] });
			queryClient.invalidateQueries({ queryKey: ["widgets", "instances"] });
		},
	});
}
