/**
 * Clean React Query Hooks for Alert System
 *
 * NO backward compatibility, uses new type system and alert service
 */

import { useQuery, useMutation, useQueryClient, UseQueryOptions, UseMutationOptions } from '@tanstack/react-query';
import type {
  EventResponse,
  Alert,
  PaginatedResponse,
  EventsSummary,
  EventQueryParams,
} from '../types/events';
import {
  getEvents,
  getEvent,
  getEventsSummary,
  acknowledgeAlert,
  resolveAlert,
  cancelAutoAction,
  dismissRecommendation,
  recordInteraction,
  acknowledgeAlertsByMetadata,
  resolveAlertsByMetadata,
  type AcknowledgeAlertResponse,
  type ResolveAlertResponse,
  type CancelAutoActionResponse,
  type DismissRecommendationResponse,
  type BulkAcknowledgeResponse,
  type BulkResolveResponse,
} from '../services/alertService';

// ============================================================
// QUERY KEYS
// ============================================================

export const alertKeys = {
  all: ['alerts'] as const,
  lists: () => [...alertKeys.all, 'list'] as const,
  list: (tenantId: string, params?: EventQueryParams) =>
    [...alertKeys.lists(), tenantId, params] as const,
  details: () => [...alertKeys.all, 'detail'] as const,
  detail: (tenantId: string, eventId: string) =>
    [...alertKeys.details(), tenantId, eventId] as const,
  summaries: () => [...alertKeys.all, 'summary'] as const,
  summary: (tenantId: string) => [...alertKeys.summaries(), tenantId] as const,
};

// ============================================================
// QUERY HOOKS
// ============================================================

/**
 * Fetch events list with filtering and pagination
 */
export function useEvents(
  tenantId: string,
  params?: EventQueryParams,
  options?: Omit<
    UseQueryOptions<PaginatedResponse<EventResponse>, Error>,
    'queryKey' | 'queryFn'
  >
) {
  return useQuery<PaginatedResponse<EventResponse>, Error>({
    queryKey: alertKeys.list(tenantId, params),
    queryFn: () => getEvents(tenantId, params),
    enabled: !!tenantId,
    staleTime: 30 * 1000, // 30 seconds
    ...options,
  });
}

/**
 * Fetch single event by ID
 */
export function useEvent(
  tenantId: string,
  eventId: string,
  options?: Omit<UseQueryOptions<EventResponse, Error>, 'queryKey' | 'queryFn'>
) {
  return useQuery<EventResponse, Error>({
    queryKey: alertKeys.detail(tenantId, eventId),
    queryFn: () => getEvent(tenantId, eventId),
    enabled: !!tenantId && !!eventId,
    staleTime: 60 * 1000, // 1 minute
    ...options,
  });
}

/**
 * Fetch events summary for dashboard
 */
export function useEventsSummary(
  tenantId: string,
  options?: Omit<UseQueryOptions<EventsSummary, Error>, 'queryKey' | 'queryFn'>
) {
  return useQuery<EventsSummary, Error>({
    queryKey: alertKeys.summary(tenantId),
    queryFn: () => getEventsSummary(tenantId),
    enabled: !!tenantId,
    staleTime: 30 * 1000, // 30 seconds
    refetchInterval: 60 * 1000, // Refetch every minute
    ...options,
  });
}

// ============================================================
// MUTATION HOOKS - Alerts
// ============================================================

interface UseAcknowledgeAlertOptions {
  tenantId: string;
  options?: UseMutationOptions<AcknowledgeAlertResponse, Error, string>;
}

/**
 * Acknowledge an alert
 */
export function useAcknowledgeAlert({
  tenantId,
  options,
}: UseAcknowledgeAlertOptions) {
  const queryClient = useQueryClient();

  return useMutation<AcknowledgeAlertResponse, Error, string>({
    mutationFn: (alertId: string) => acknowledgeAlert(tenantId, alertId),
    onSuccess: (data, alertId) => {
      // Invalidate relevant queries
      queryClient.invalidateQueries({ queryKey: alertKeys.lists() });
      queryClient.invalidateQueries({ queryKey: alertKeys.summaries() });
      queryClient.invalidateQueries({
        queryKey: alertKeys.detail(tenantId, alertId),
      });

      // Call user's onSuccess if provided (passing the context as well)
      if (options?.onSuccess) {
        options.onSuccess(data, alertId, {} as any);
      }
    },
    ...options,
  });
}

interface UseResolveAlertOptions {
  tenantId: string;
  options?: UseMutationOptions<ResolveAlertResponse, Error, string>;
}

/**
 * Resolve an alert
 */
export function useResolveAlert({ tenantId, options }: UseResolveAlertOptions) {
  const queryClient = useQueryClient();

  return useMutation<ResolveAlertResponse, Error, string>({
    mutationFn: (alertId: string) => resolveAlert(tenantId, alertId),
    onSuccess: (data, alertId) => {
      // Invalidate relevant queries
      queryClient.invalidateQueries({ queryKey: alertKeys.lists() });
      queryClient.invalidateQueries({ queryKey: alertKeys.summaries() });
      queryClient.invalidateQueries({
        queryKey: alertKeys.detail(tenantId, alertId),
      });

      // Call user's onSuccess if provided (passing the context as well)
      if (options?.onSuccess) {
        options.onSuccess(data, alertId, {} as any);
      }
    },
    ...options,
  });
}

interface UseCancelAutoActionOptions {
  tenantId: string;
  options?: UseMutationOptions<CancelAutoActionResponse, Error, string>;
}

/**
 * Cancel an alert's auto-action (escalation countdown)
 */
export function useCancelAutoAction({
  tenantId,
  options,
}: UseCancelAutoActionOptions) {
  const queryClient = useQueryClient();

  return useMutation<CancelAutoActionResponse, Error, string>({
    mutationFn: (alertId: string) => cancelAutoAction(tenantId, alertId),
    onSuccess: (data, alertId) => {
      // Invalidate relevant queries
      queryClient.invalidateQueries({ queryKey: alertKeys.lists() });
      queryClient.invalidateQueries({
        queryKey: alertKeys.detail(tenantId, alertId),
      });

      // Call user's onSuccess if provided (passing the context as well)
      if (options?.onSuccess) {
        options.onSuccess(data, alertId, {} as any);
      }
    },
    ...options,
  });
}

// ============================================================
// MUTATION HOOKS - Recommendations
// ============================================================

interface UseDismissRecommendationOptions {
  tenantId: string;
  options?: UseMutationOptions<DismissRecommendationResponse, Error, string>;
}

/**
 * Dismiss a recommendation
 */
export function useDismissRecommendation({
  tenantId,
  options,
}: UseDismissRecommendationOptions) {
  const queryClient = useQueryClient();

  return useMutation<DismissRecommendationResponse, Error, string>({
    mutationFn: (recommendationId: string) =>
      dismissRecommendation(tenantId, recommendationId),
    onSuccess: (data, recommendationId) => {
      // Invalidate relevant queries
      queryClient.invalidateQueries({ queryKey: alertKeys.lists() });
      queryClient.invalidateQueries({ queryKey: alertKeys.summaries() });
      queryClient.invalidateQueries({
        queryKey: alertKeys.detail(tenantId, recommendationId),
      });

      // Call user's onSuccess if provided
      options?.onSuccess?.(data, recommendationId, undefined);
    },
    ...options,
  });
}

// ============================================================
// MUTATION HOOKS - Bulk Operations
// ============================================================

interface UseBulkAcknowledgeOptions {
  tenantId: string;
  options?: UseMutationOptions<
    BulkAcknowledgeResponse,
    Error,
    { alertType: string; metadataFilter: Record<string, any> }
  >;
}

/**
 * Acknowledge multiple alerts by metadata
 */
export function useBulkAcknowledgeAlerts({
  tenantId,
  options,
}: UseBulkAcknowledgeOptions) {
  const queryClient = useQueryClient();

  return useMutation<
    BulkAcknowledgeResponse,
    Error,
    { alertType: string; metadataFilter: Record<string, any> }
  >({
    mutationFn: ({ alertType, metadataFilter }) =>
      acknowledgeAlertsByMetadata(tenantId, alertType, metadataFilter),
    onSuccess: (data, variables) => {
      // Invalidate all alert queries
      queryClient.invalidateQueries({ queryKey: alertKeys.lists() });
      queryClient.invalidateQueries({ queryKey: alertKeys.summaries() });

      // Call user's onSuccess if provided (passing the context as well)
      if (options?.onSuccess) {
        options.onSuccess(data, variables, {} as any);
      }
    },
    ...options,
  });
}

interface UseBulkResolveOptions {
  tenantId: string;
  options?: UseMutationOptions<
    BulkResolveResponse,
    Error,
    { alertType: string; metadataFilter: Record<string, any> }
  >;
}

/**
 * Resolve multiple alerts by metadata
 */
export function useBulkResolveAlerts({
  tenantId,
  options,
}: UseBulkResolveOptions) {
  const queryClient = useQueryClient();

  return useMutation<
    BulkResolveResponse,
    Error,
    { alertType: string; metadataFilter: Record<string, any> }
  >({
    mutationFn: ({ alertType, metadataFilter }) =>
      resolveAlertsByMetadata(tenantId, alertType, metadataFilter),
    onSuccess: (data, variables) => {
      // Invalidate all alert queries
      queryClient.invalidateQueries({ queryKey: alertKeys.lists() });
      queryClient.invalidateQueries({ queryKey: alertKeys.summaries() });

      // Call user's onSuccess if provided (passing the context as well)
      if (options?.onSuccess) {
        options.onSuccess(data, variables, {} as any);
      }
    },
    ...options,
  });
}

// ============================================================
// MUTATION HOOKS - Interaction Tracking
// ============================================================

interface UseRecordInteractionOptions {
  tenantId: string;
  options?: UseMutationOptions<
    any,
    Error,
    { eventId: string; interactionType: string; metadata?: Record<string, any> }
  >;
}

/**
 * Record user interaction with an event
 */
export function useRecordInteraction({
  tenantId,
  options,
}: UseRecordInteractionOptions) {
  return useMutation<
    any,
    Error,
    { eventId: string; interactionType: string; metadata?: Record<string, any> }
  >({
    mutationFn: ({ eventId, interactionType, metadata }) =>
      recordInteraction(tenantId, eventId, interactionType, metadata),
    ...options,
  });
}
