import { logger } from '../../utils/logger';
import db from '../../config/database';

export interface Alert {
  id?: number;
  tenantId: string;
  module: string;
  level: 'INFO' | 'WARN' | 'ERROR' | 'CRITICAL';
  message: string;
  metadata?: any;
  status: 'OPEN' | 'ACKNOWLEDGED' | 'RESOLVED';
  createdAt: Date;
}

/**
 * [CORE_TELE_ALRT] 统一告警归集与自愈路由 (Alert Hub)
 * @description 核心逻辑：将全站（风控、自愈、时效、系统健康度）的异常事件统一接入告警中枢。
 * 支持按租户聚合告警，并为 AGI 提供自愈决策的输入上下文。
 */
export class AlertService {
  private static readonly ALERT_TABLE = 'cf_system_alerts';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.ALERT_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.ALERT_TABLE} table...`);
      await db.schema.createTable(this.ALERT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).index();
        table.string('module', 32).notNullable();
        table.string('level', 16).notNullable();
        table.string('message', 512).notNullable();
        table.json('metadata');
        table.string('status', 16).defaultTo('OPEN');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenant_id', 'status', 'level']);
      });
      logger.info(`✅ Table ${this.ALERT_TABLE} created`);
    }
  }

  /**
   * 触发告警 (Trigger Alert)
   */
  static async triggerAlert(alert: Omit<Alert, 'id' | 'createdAt' | 'status'>): Promise<number> {
    logger.warn(`[AlertHub] [${alert.level}] ${alert.module}: ${alert.message}`);

    try {
      const [id] = await db(this.ALERT_TABLE).insert({
        tenant_id: alert.tenantId,
        module: alert.module,
        level: alert.level,
        message: alert.message,
        metadata: alert.metadata ? JSON.stringify(alert.metadata) : null,
        status: 'OPEN',
        created_at: new Date()
      });

      // TODO: 联动 Webhook 或钉钉/飞书通知告警
      
      return id;
    } catch (err: any) {
      logger.error(`[AlertHub] Failed to trigger alert: ${err.message}`);
      return -1;
    }
  }

  /**
   * 获取租户活跃告警
   */
  static async getActiveAlerts(tenantId: string): Promise<Alert[]> {
    const records = await db(this.ALERT_TABLE)
      .where({ tenant_id: tenantId })
      .whereIn('status', ['OPEN', 'ACKNOWLEDGED'])
      .orderBy('created_at', 'desc');

    return records.map(r => ({
      id: r.id,
      tenantId: r.tenant_id,
      module: r.module,
      level: r.level as any,
      message: r.message,
      metadata: r.metadata ? JSON.parse(r.metadata) : null,
      status: r.status as any,
      createdAt: r.created_at
    }));
  }

  /**
   * 标记告警为已解决
   */
  static async resolveAlert(alertId: number) {
    await db(this.ALERT_TABLE).where({ id: alertId }).update({
      status: 'RESOLVED',
      created_at: new Date() // 使用 created_at 作为解决时间或新增 resolved_at
    });
  }
}
