'use client';

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';

import { apiFetch } from '@/lib/api/client';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import type { AlertCountResponse, AlertListResponse, AlertStatus } from './types';

export function useAlertList(status: AlertStatus = 'open', enabled = true) {
  return useQuery<AlertListResponse>({
    queryKey: ['alerts', status],
    queryFn: () => apiFetch<AlertListResponse>(`/api/v1/alerts?status=${status}`),
    staleTime: 30_000,
    enabled,
  });
}

export function useAlertCount() {
  return useQuery<AlertCountResponse>({
    queryKey: ['alerts', 'count'],
    queryFn: () => apiFetch<AlertCountResponse>('/api/v1/alerts/count'),
    staleTime: 30_000,
  });
}

export function useAlertActions() {
  const queryClient = useQueryClient();
  const invalidate = () => {
    queryClient.invalidateQueries({ queryKey: ['alerts'] });
  };

  const acknowledge = useMutation({
    mutationFn: (id: string) => apiFetch(`/api/v1/alerts/${id}/acknowledge`, { method: 'POST' }),
    onSuccess: invalidate,
  });
  const dismiss = useMutation({
    mutationFn: (id: string) => apiFetch(`/api/v1/alerts/${id}/dismiss`, { method: 'POST' }),
    onSuccess: invalidate,
  });

  return { acknowledge, dismiss };
}

export function useDismissAll() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (filter: { ruleId?: string; severity?: string } = {}) =>
      apiFetch('/api/v1/alerts/dismiss-all', { method: 'POST', body: filter }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['alerts'] }),
  });
}

export function useAlertRealtime() {
  useRealtimeInvalidation({
    'alert:created': [['alerts']],
    'alert:resolved': [['alerts']],
    'alert:dismissed': [['alerts']],
  });
}
