-- Alert System Database Migration
-- Creates tables for alert logs, templates, delivery tracking, and usage analytics

-- Alert Logs Table
CREATE TABLE IF NOT EXISTS alert_logs (
  id TEXT PRIMARY KEY,
  alert_type TEXT NOT NULL,
  severity TEXT NOT NULL CHECK(severity IN ('critical', 'warning', 'info')),
  message TEXT NOT NULL,
  status TEXT NOT NULL CHECK(status IN ('active', 'acknowledged', 'resolved')),
  team TEXT,
  escalation_count INTEGER DEFAULT 0,
  acknowledged_at INTEGER,
  resolved_at INTEGER,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL
);

-- Create indexes for alert_logs
CREATE INDEX IF NOT EXISTS alert_logs_type_idx ON alert_logs(alert_type);
CREATE INDEX IF NOT EXISTS alert_logs_severity_idx ON alert_logs(severity);
CREATE INDEX IF NOT EXISTS alert_logs_status_idx ON alert_logs(status);
CREATE INDEX IF NOT EXISTS alert_logs_team_idx ON alert_logs(team);
CREATE INDEX IF NOT EXISTS alert_logs_created_at_idx ON alert_logs(created_at);

-- Alert Templates Table
CREATE TABLE IF NOT EXISTS alert_templates (
  id TEXT PRIMARY KEY,
  alert_type TEXT NOT NULL UNIQUE,
  title TEXT NOT NULL,
  description TEXT,
  slack_template TEXT NOT NULL,
  email_template TEXT NOT NULL,
  pagerduty_template TEXT NOT NULL,
  variables TEXT,
  severity TEXT NOT NULL CHECK(severity IN ('critical', 'warning', 'info')),
  enabled INTEGER DEFAULT 1,
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL
);

-- Create indexes for alert_templates
CREATE INDEX IF NOT EXISTS alert_templates_type_idx ON alert_templates(alert_type);
CREATE INDEX IF NOT EXISTS alert_templates_enabled_idx ON alert_templates(enabled);

-- Alert Delivery Logs Table
CREATE TABLE IF NOT EXISTS alert_delivery_logs (
  id TEXT PRIMARY KEY,
  alert_id TEXT NOT NULL,
  channel TEXT NOT NULL CHECK(channel IN ('slack', 'email', 'pagerduty')),
  status TEXT NOT NULL CHECK(status IN ('pending', 'sent', 'failed')),
  recipient TEXT,
  error TEXT,
  retry_count INTEGER DEFAULT 0,
  next_retry_at INTEGER,
  sent_at INTEGER,
  created_at INTEGER NOT NULL,
  FOREIGN KEY (alert_id) REFERENCES alert_logs(id) ON DELETE CASCADE
);

-- Create indexes for alert_delivery_logs
CREATE INDEX IF NOT EXISTS alert_delivery_logs_alert_id_idx ON alert_delivery_logs(alert_id);
CREATE INDEX IF NOT EXISTS alert_delivery_logs_channel_idx ON alert_delivery_logs(channel);
CREATE INDEX IF NOT EXISTS alert_delivery_logs_status_idx ON alert_delivery_logs(status);

-- Alert Template Usage Table
CREATE TABLE IF NOT EXISTS alert_template_usage (
  id TEXT PRIMARY KEY,
  template_id TEXT NOT NULL,
  alert_id TEXT NOT NULL,
  used_at INTEGER NOT NULL,
  delivery_success INTEGER,
  acknowledged_within INTEGER,
  resolved_within INTEGER,
  FOREIGN KEY (template_id) REFERENCES alert_templates(id) ON DELETE CASCADE,
  FOREIGN KEY (alert_id) REFERENCES alert_logs(id) ON DELETE CASCADE
);

-- Create indexes for alert_template_usage
CREATE INDEX IF NOT EXISTS alert_template_usage_template_id_idx ON alert_template_usage(template_id);
CREATE INDEX IF NOT EXISTS alert_template_usage_alert_id_idx ON alert_template_usage(alert_id);

-- Insert default alert templates
INSERT OR IGNORE INTO alert_templates (id, alert_type, title, description, slack_template, email_template, pagerduty_template, variables, severity, enabled, created_at, updated_at) VALUES
('template-latency-critical', 'latency_critical', 'Critical Latency Alert', 'WebSocket latency exceeded threshold', '🚨 *Critical Latency Alert*\nLatency: {{latency}}ms\nThreshold: {{threshold}}ms', '<h2>Critical Latency Alert</h2><p>Latency: {{latency}}ms</p><p>Threshold: {{threshold}}ms</p>', 'Critical Latency: {{latency}}ms', '["latency","threshold"]', 'critical', 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000),
('template-delivery-failure', 'delivery_failure', 'Delivery Failure Alert', 'Email/SMS delivery rate degraded', '⚠️ *Delivery Failure Alert*\nSuccess Rate: {{successRate}}%\nChannel: {{channel}}', '<h2>Delivery Failure Alert</h2><p>Success Rate: {{successRate}}%</p><p>Channel: {{channel}}</p>', 'Delivery Failure: {{channel}} at {{successRate}}%', '["successRate","channel"]', 'warning', 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000),
('template-forecast-accuracy', 'forecast_accuracy_degrading', 'Forecast Accuracy Degraded', 'Revenue forecast model accuracy below threshold', '📊 *Forecast Accuracy Alert*\nAccuracy: {{accuracy}}%\nThreshold: {{threshold}}%', '<h2>Forecast Accuracy Alert</h2><p>Accuracy: {{accuracy}}%</p><p>Threshold: {{threshold}}%</p>', 'Forecast Accuracy: {{accuracy}}%', '["accuracy","threshold"]', 'warning', 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000),
('template-connection-drop', 'connection_drop', 'Connection Drop Alert', 'WebSocket connection drop detected', '🔌 *Connection Drop Alert*\nConnections Lost: {{count}}\nRecovered: {{recovered}}', '<h2>Connection Drop Alert</h2><p>Connections Lost: {{count}}</p><p>Recovered: {{recovered}}</p>', 'Connection Drop: {{count}} connections', '["count","recovered"]', 'info', 1, strftime('%s', 'now') * 1000, strftime('%s', 'now') * 1000);
