import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
	createDashboard,
	deleteDashboard,
	fetchDashboardBySlug,
	fetchDashboards,
	updateDashboard,
	type NamedDashboardInput,
} from "../api/dashboards";

export function useDashboards() {
	return useQuery({
		queryKey: ["dashboards"],
		queryFn: fetchDashboards,
		staleTime: 30 * 1000,
	});
}

export function useDashboardBySlug(slug: string | undefined) {
	return useQuery({
		queryKey: ["dashboards", "slug", slug],
		queryFn: () => fetchDashboardBySlug(slug!),
		enabled: !!slug,
		staleTime: 30 * 1000,
	});
}

export function useSaveDashboard() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (input: NamedDashboardInput) =>
			input.id ? updateDashboard(input) : createDashboard(input),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["dashboards"] });
		},
	});
}

export function useDeleteDashboard() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (id: string) => deleteDashboard(id),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["dashboards"] });
		},
	});
}
