import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
    acknowledgeBackupAlert,
    fetchBackupAlerts,
    fetchBackupDashboard,
    fetchBackupJob,
    fetchBackupJobs,
    fetchBackupRuns,
} from "../api/backups";

export function useBackupJobs() {
    return useQuery({
        queryKey: ["backups", "jobs"],
        queryFn: fetchBackupJobs,
        refetchInterval: 30_000,
    });
}

export function useBackupJob(jobId: string) {
    return useQuery({
        queryKey: ["backups", "jobs", jobId],
        queryFn: () => fetchBackupJob(jobId),
        enabled: !!jobId,
    });
}

export function useBackupRuns(jobId?: string, status?: string) {
    return useQuery({
        queryKey: ["backups", "runs", jobId, status],
        queryFn: () => fetchBackupRuns(jobId, status),
        refetchInterval: 15_000,
    });
}

export function useBackupAlerts(jobId?: string, acknowledged?: boolean, severity?: string) {
    return useQuery({
        queryKey: ["backups", "alerts", jobId, acknowledged, severity],
        queryFn: () => fetchBackupAlerts(jobId, acknowledged, severity),
        refetchInterval: 30_000,
    });
}

export function useAcknowledgeAlert() {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: acknowledgeBackupAlert,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["backups", "alerts"] });
        },
    });
}

export function useBackupDashboard() {
    return useQuery({
        queryKey: ["dashboard", "backups"],
        queryFn: fetchBackupDashboard,
        refetchInterval: 30_000,
    });
}
