/**
 * Alert Analytics API Client
 * Handles all API calls for alert analytics and interaction tracking
 */

import { apiClient } from '../client';

export interface AlertTrendData {
  date: string;
  count: number;
  urgentCount: number;
  highCount: number;
  mediumCount: number;
  lowCount: number;
}

export interface AlertCategory {
  category: string;
  count: number;
  percentage: number;
}

export interface AlertAnalytics {
  trends: AlertTrendData[];
  averageResponseTime: number;
  topCategories: AlertCategory[];
  totalAlerts: number;
  resolvedAlerts: number;
  activeAlerts: number;
  resolutionRate: number;
  predictedDailyAverage: number;
  busiestDay: string;
}

export interface AlertInteraction {
  alert_id: string;
  interaction_type: 'acknowledged' | 'resolved' | 'snoozed' | 'dismissed';
  metadata?: Record<string, any>;
}

export interface InteractionResponse {
  id: string;
  alert_id: string;
  interaction_type: string;
  interacted_at: string;
  response_time_seconds: number;
}

export interface BatchInteractionResponse {
  created_count: number;
  interactions: Array<{
    id: string;
    alert_id: string;
    interaction_type: string;
    interacted_at: string;
  }>;
}

/**
 * Track a single alert interaction
 */
export async function trackAlertInteraction(
  tenantId: string,
  alertId: string,
  interactionType: 'acknowledged' | 'resolved' | 'snoozed' | 'dismissed',
  metadata?: Record<string, any>
): Promise<InteractionResponse> {
  return apiClient.post<InteractionResponse>(
    `/tenants/${tenantId}/alerts/${alertId}/interactions`,
    {
      alert_id: alertId,
      interaction_type: interactionType,
      metadata
    }
  );
}

/**
 * Track multiple alert interactions in batch
 */
export async function trackAlertInteractionsBatch(
  tenantId: string,
  interactions: AlertInteraction[]
): Promise<BatchInteractionResponse> {
  return apiClient.post<BatchInteractionResponse>(
    `/tenants/${tenantId}/alerts/interactions/batch`,
    {
      interactions
    }
  );
}

/**
 * Get comprehensive alert analytics
 */
export async function getAlertAnalytics(
  tenantId: string,
  days: number = 7
): Promise<AlertAnalytics> {
  console.log('[getAlertAnalytics] Calling API:', `/tenants/${tenantId}/alerts/analytics`, 'with days:', days);
  const data = await apiClient.get<AlertAnalytics>(
    `/tenants/${tenantId}/alerts/analytics`,
    {
      params: { days }
    }
  );
  console.log('[getAlertAnalytics] Received data:', data);
  console.log('[getAlertAnalytics] Data type:', typeof data);
  return data; // apiClient.get() already returns data, not response.data
}

/**
 * Get alert trends only
 */
export async function getAlertTrends(
  tenantId: string,
  days: number = 7
): Promise<AlertTrendData[]> {
  return apiClient.get<AlertTrendData[]>(
    `/tenants/${tenantId}/alerts/analytics/trends`,
    {
      params: { days }
    }
  );
}
