/**
 * Alert Processor service TypeScript type definitions
 * Mirrored from backend alert processing schemas
 */

// Enums
export enum AlertItemType {
  ALERT = 'alert',
  RECOMMENDATION = 'recommendation',
}

export enum AlertType {
  INVENTORY_LOW = 'inventory_low',
  QUALITY_ISSUE = 'quality_issue', 
  DELIVERY_DELAY = 'delivery_delay',
  PRODUCTION_DELAY = 'production_delay',
  EQUIPMENT_FAILURE = 'equipment_failure',
  FOOD_SAFETY = 'food_safety',
  TEMPERATURE_ALERT = 'temperature_alert',
  EXPIRY_WARNING = 'expiry_warning',
  FORECAST_ACCURACY = 'forecast_accuracy',
  DEMAND_SPIKE = 'demand_spike',
  SUPPLIER_ISSUE = 'supplier_issue',
  COST_OPTIMIZATION = 'cost_optimization',
  REVENUE_OPPORTUNITY = 'revenue_opportunity',
}

export enum AlertSeverity {
  URGENT = 'urgent',
  HIGH = 'high', 
  MEDIUM = 'medium',
  LOW = 'low',
}

export enum AlertService {
  INVENTORY = 'inventory',
  PRODUCTION = 'production',
  SUPPLIERS = 'suppliers',
  FORECASTING = 'forecasting',
  QUALITY = 'quality',
  FINANCE = 'finance',
  OPERATIONS = 'operations',
}

export enum NotificationChannel {
  WHATSAPP = 'whatsapp',
  EMAIL = 'email', 
  PUSH = 'push',
  DASHBOARD = 'dashboard',
  SMS = 'sms',
}

// Core alert data structures
export interface AlertAction {
  action: string;
  label: string;
  endpoint?: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  payload?: Record<string, any>;
}

export interface AlertMessage {
  id: string;
  tenant_id: string;
  item_type: AlertItemType;
  type: AlertType;
  severity: AlertSeverity;
  service: AlertService;
  title: string;
  message: string;
  actions: AlertAction[];
  metadata: Record<string, any>;
  timestamp: string; // ISO 8601 date string
}

// Channel routing configuration
export interface ChannelRoutingConfig {
  urgent: NotificationChannel[];
  high: NotificationChannel[];
  medium: NotificationChannel[];
  low: NotificationChannel[];
  recommendations: NotificationChannel[];
}

export interface BusinessHours {
  start_hour: number; // 0-23
  end_hour: number;   // 0-23
  days: number[];     // 0-6, Sunday=0
  timezone?: string;  // e.g., 'Europe/Madrid'
}

export interface NotificationSettings {
  tenant_id: string;
  channels_enabled: NotificationChannel[];
  business_hours: BusinessHours;
  emergency_contacts: {
    whatsapp?: string;
    email?: string;
    sms?: string;
  };
  channel_preferences: {
    [key in AlertSeverity]?: NotificationChannel[];
  };
}

// Processing status and metrics
export interface ProcessingMetrics {
  total_processed: number;
  successful: number;
  failed: number;
  retries: number;
  average_processing_time_ms: number;
}

export interface AlertProcessingStatus {
  alert_id: string;
  tenant_id: string;
  status: 'pending' | 'processing' | 'completed' | 'failed' | 'retrying';
  created_at: string;
  processed_at?: string;
  error_message?: string;
  retry_count: number;
  channels_sent: NotificationChannel[];
  delivery_status: {
    [channel in NotificationChannel]?: {
      status: 'pending' | 'sent' | 'delivered' | 'failed';
      sent_at?: string;
      delivered_at?: string;
      error?: string;
    };
  };
}

// Queue message structures (for RabbitMQ integration)
export interface QueueMessage {
  id: string;
  routing_key: string;
  exchange: string;
  payload: AlertMessage;
  headers?: Record<string, any>;
  properties?: {
    delivery_mode?: number;
    priority?: number;
    correlation_id?: string;
    reply_to?: string;
    expiration?: string;
    message_id?: string;
    timestamp?: number;
    type?: string;
    user_id?: string;
    app_id?: string;
  };
}

// SSE (Server-Sent Events) message types for real-time updates
export interface SSEAlertMessage {
  type: 'alert' | 'recommendation' | 'alert_update' | 'system_status';
  data: AlertMessage | AlertProcessingStatus | SystemStatusMessage;
  timestamp: string;
}

export interface SystemStatusMessage {
  service: 'alert_processor';
  status: 'healthy' | 'degraded' | 'down';
  message?: string;
  metrics: ProcessingMetrics;
}

// Dashboard integration types
export interface AlertDashboardData {
  active_alerts: AlertMessage[];
  recent_recommendations: AlertMessage[];
  severity_counts: {
    [key in AlertSeverity]: number;
  };
  service_breakdown: {
    [key in AlertService]: number;
  };
  processing_stats: ProcessingMetrics;
}

export interface AlertFilters {
  severity?: AlertSeverity[];
  type?: AlertType[];
  service?: AlertService[];
  item_type?: AlertItemType[];
  date_from?: string; // ISO 8601 date string
  date_to?: string;   // ISO 8601 date string
  status?: 'active' | 'acknowledged' | 'resolved' | 'dismissed';
  search?: string;
}

export interface AlertQueryParams extends AlertFilters {
  limit?: number;
  offset?: number;
  sort_by?: 'timestamp' | 'severity' | 'type';
  sort_order?: 'asc' | 'desc';
}

// Alert lifecycle management
export interface AlertUpdateRequest {
  status?: 'acknowledged' | 'resolved' | 'dismissed';
  notes?: string;
  assigned_to?: string;
  priority_override?: AlertSeverity;
}

export interface AlertResponse extends AlertMessage {
  status: 'active' | 'acknowledged' | 'resolved' | 'dismissed';
  created_at: string;
  updated_at?: string;
  acknowledged_at?: string;
  acknowledged_by?: string;
  resolved_at?: string;
  resolved_by?: string;
  notes?: string;
  assigned_to?: string;
}

// Webhook integration for external systems
export interface WebhookConfig {
  tenant_id: string;
  webhook_url: string;
  secret_token: string;
  enabled: boolean;
  event_types: (AlertType | 'all')[];
  severity_filter: AlertSeverity[];
  headers?: Record<string, string>;
  retry_config: {
    max_retries: number;
    retry_delay_ms: number;
    backoff_multiplier: number;
  };
}

export interface WebhookPayload {
  event_type: 'alert_created' | 'alert_updated' | 'alert_resolved';
  alert: AlertResponse;
  tenant_id: string;
  webhook_id: string;
  timestamp: string;
  signature: string; // HMAC signature for verification
}

// API Response Wrappers
export interface PaginatedResponse<T> {
  data: T[];
  total: number;
  limit: number;
  offset: number;
  has_next: boolean;
  has_previous: boolean;
}

export interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
  errors?: string[];
}

// Export all types
export type {
  // Add any additional export aliases if needed
};