/**
 * Alert System Database Schema
 * Defines tables for alert logs and notification templates
 */

import { sqliteTable, text, integer, real, index } from 'drizzle-orm/sqlite-core';

/**
 * Alert Logs Table
 * Stores all alerts for audit trail and compliance
 */
export const alertLogs = sqliteTable(
  'alert_logs',
  {
    id: text('id').primaryKey(),
    alertType: text('alert_type').notNull(),
    severity: text('severity').notNull(), // 'critical', 'warning', 'info'
    message: text('message').notNull(),
    status: text('status').notNull(), // 'active', 'acknowledged', 'resolved'
    team: text('team'), // 'ops', 'support', 'analytics', etc.
    escalationCount: integer('escalation_count').default(0),
    acknowledgedAt: integer('acknowledged_at'), // Unix timestamp
    resolvedAt: integer('resolved_at'), // Unix timestamp
    createdAt: integer('created_at').notNull(), // Unix timestamp
    updatedAt: integer('updated_at').notNull(), // Unix timestamp
  },
  (table) => ({
    alertTypeIdx: index('alert_logs_type_idx').on(table.alertType),
    severityIdx: index('alert_logs_severity_idx').on(table.severity),
    statusIdx: index('alert_logs_status_idx').on(table.status),
    teamIdx: index('alert_logs_team_idx').on(table.team),
    createdAtIdx: index('alert_logs_created_at_idx').on(table.createdAt),
  })
);

/**
 * Alert Notification Templates Table
 * Stores customizable templates for different alert types
 */
export const alertTemplates = sqliteTable(
  'alert_templates',
  {
    id: text('id').primaryKey(),
    alertType: text('alert_type').notNull().unique(),
    title: text('title').notNull(),
    description: text('description'),
    slackTemplate: text('slack_template').notNull(), // Template with {{variables}}
    emailTemplate: text('email_template').notNull(), // HTML template
    pagerdutyTemplate: text('pagerduty_template').notNull(), // PagerDuty format
    variables: text('variables'), // JSON array of variable names
    severity: text('severity').notNull(), // 'critical', 'warning', 'info'
    enabled: integer('enabled').default(1), // 0 or 1
    createdAt: integer('created_at').notNull(),
    updatedAt: integer('updated_at').notNull(),
  },
  (table) => ({
    alertTypeIdx: index('alert_templates_type_idx').on(table.alertType),
    enabledIdx: index('alert_templates_enabled_idx').on(table.enabled),
  })
);

/**
 * Alert Delivery Logs Table
 * Tracks delivery attempts for each alert
 */
export const alertDeliveryLogs = sqliteTable(
  'alert_delivery_logs',
  {
    id: text('id').primaryKey(),
    alertId: text('alert_id').notNull(),
    channel: text('channel').notNull(), // 'slack', 'email', 'pagerduty'
    status: text('status').notNull(), // 'pending', 'sent', 'failed'
    recipient: text('recipient'), // Email, Slack channel, PagerDuty service
    error: text('error'), // Error message if failed
    retryCount: integer('retry_count').default(0),
    nextRetryAt: integer('next_retry_at'), // Unix timestamp
    sentAt: integer('sent_at'), // Unix timestamp
    createdAt: integer('created_at').notNull(),
  },
  (table) => ({
    alertIdIdx: index('alert_delivery_logs_alert_id_idx').on(table.alertId),
    channelIdx: index('alert_delivery_logs_channel_idx').on(table.channel),
    statusIdx: index('alert_delivery_logs_status_idx').on(table.status),
  })
);

/**
 * Alert Template Usage Table
 * Tracks which templates are used and their effectiveness
 */
export const alertTemplateUsage = sqliteTable(
  'alert_template_usage',
  {
    id: text('id').primaryKey(),
    templateId: text('template_id').notNull(),
    alertId: text('alert_id').notNull(),
    usedAt: integer('used_at').notNull(), // Unix timestamp
    deliverySuccess: integer('delivery_success'), // 0 or 1
    acknowledgedWithin: integer('acknowledged_within'), // Minutes to acknowledge
    resolvedWithin: integer('resolved_within'), // Minutes to resolve
  },
  (table) => ({
    templateIdIdx: index('alert_template_usage_template_id_idx').on(table.templateId),
    alertIdIdx: index('alert_template_usage_alert_id_idx').on(table.alertId),
  })
);

export type AlertLog = typeof alertLogs.$inferSelect;
export type AlertLogInsert = typeof alertLogs.$inferInsert;

export type AlertTemplate = typeof alertTemplates.$inferSelect;
export type AlertTemplateInsert = typeof alertTemplates.$inferInsert;

export type AlertDeliveryLog = typeof alertDeliveryLogs.$inferSelect;
export type AlertDeliveryLogInsert = typeof alertDeliveryLogs.$inferInsert;

export type AlertTemplateUsage = typeof alertTemplateUsage.$inferSelect;
export type AlertTemplateUsageInsert = typeof alertTemplateUsage.$inferInsert;
