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

export interface SensitiveAction {
  tenantId: string;
  userId: string;
  actionType: string;
  resourceId: string;
  payload: any;
}

/**
 * [BIZ_KER_133] 租户敏感操作二次确认审计 (Action Audit)
 * @description 核心逻辑：拦截并审计租户的敏感操作（如删除核心配置、大额退款等）。
 * 强制执行二次确认逻辑（配合前端 UI），并记录完整的操作轨迹与 AGI 风险评估。
 * 联动语义日志中心输出主权安全审计报告。
 * 遵循 Autocomplete-First (V31.5) 规范。
 */
export class ActionAuditService {
  private static readonly AUDIT_TABLE = 'cf_sensitive_action_logs';

  /**
   * 初始化审计表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.AUDIT_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.AUDIT_TABLE} table...`);
      await db.schema.createTable(this.AUDIT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('user_id', 64).notNullable();
        table.string('action_type', 64).notNullable();
        table.string('resource_id', 128);
        table.json('payload');
        table.string('risk_level', 16).defaultTo('LOW');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenant_id', 'action_type']);
      });
      logger.info(`✅ Table ${this.AUDIT_TABLE} created`);
    }
  }

  /**
   * 记录并评估敏感操作
   * @param action 操作详情
   */
  static async auditAction(action: SensitiveAction) {
    logger.info(`[ActionAudit] Auditing sensitive action: ${action.actionType} for Tenant ${action.tenantId}`);

    // 1. AGI 风险评估 (模拟)
    const riskLevel = this.evaluateRisk(action);

    // 2. 存储审计日志
    await db(this.AUDIT_TABLE).insert({
      tenant_id: action.tenantId,
      user_id: action.userId,
      action_type: action.actionType,
      resource_id: action.resourceId,
      payload: JSON.stringify(action.payload),
      risk_level: riskLevel
    });

    // 3. 针对高风险操作输出语义日志报告
    if (riskLevel === 'HIGH' || riskLevel === 'CRITICAL') {
      const report = this.generateReport(action, riskLevel);
      await SemanticLogService.logSemantic(report, 'ERROR', 'SOVEREIGN_SECURITY');
    }
  }

  private static evaluateRisk(action: SensitiveAction): string {
    const highRiskTypes = ['DELETE_TENANT', 'BULK_REFUND', 'CHANGE_MASTER_KEY'];
    if (highRiskTypes.includes(action.actionType)) return 'CRITICAL';
    if (action.actionType.includes('DELETE') || action.actionType.includes('UPDATE_CONFIG')) return 'HIGH';
    return 'LOW';
  }

  private static generateReport(action: SensitiveAction, risk: string): string {
    return `### 🛡️ Sovereign Security: High-Risk Action Detected\n\n` +
           `**Tenant:** ${action.tenantId} | **User:** ${action.userId}\n` +
           `**Action:** \`${action.actionType}\` | **Resource:** \`${action.resourceId}\`\n` +
           `**Risk Level:** [ ${risk} ]\n\n` +
           `**Payload Snapshot:** \`${JSON.stringify(action.payload)}\`\n\n` +
           `**Recommendation:** 此操作涉及主权安全或核心资产变更，请确保已通过人工二次确认流程。`;
  }
}
