import { useQuery } from '@tanstack/react-query';
import { supabase } from '@/lib/supabaseClient';
import { queryKeys } from '@/lib/queryKeys';

export interface CorrelatedAlert {
  rule_id: string;
  rule_name: string;
  rule_description: string;
  incident_severity: 'critical' | 'high' | 'medium' | 'low';
  incident_title_template: string;
  time_window_minutes: number;
  min_alerts_required: number;
  matching_alerts_count: number;
  alert_ids: string[];
  alert_sources: string[];
  alert_messages: string[];
  first_alert_at: string;
  last_alert_at: string;
  can_create_incident: boolean;
}

export function useCorrelatedAlerts() {
  return useQuery({
    queryKey: queryKeys.monitoring.correlatedAlerts(),
    queryFn: async () => {
      const { data, error } = await supabase
        .from('alert_correlations_view')
        .select('*')
        .order('incident_severity', { ascending: true })
        .order('matching_alerts_count', { ascending: false });

      if (error) throw error;
      return (data || []) as CorrelatedAlert[];
    },
    staleTime: 15000,
    refetchInterval: 30000,
  });
}
