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

/**
 * [BIZ_FIN_200] 基于 AGI 的全自动审计与合规性自查 (Self-Audit)
 * @description 最终防线，基于 AGI 的全量合规自查。
 */
export class ComplianceAIGuard {
  private static readonly GUARD_TABLE = 'cf_compliance_ai_audits';

  /**
   * 执行合规自查
   */
  static async performSelfAudit(tenantId: string) {
    logger.info(`[ComplianceAIGuard] Performing self-audit for tenant: ${tenantId}`);

    // 1. 获取最近一天的财务变动记录
    const dayStart = new Date();
    dayStart.setHours(0, 0, 0, 0);

    const audits = await db('cf_audit_logs')
      .where({ tenantId })
      .andWhere('created_at', '>=', dayStart)
      .select('id', 'action', 'actorId', 'resourceId');

    const auditResults = [];

    for (const audit of audits) {
      const { id, action, actorId, resourceId } = audit;
      
      // 2. 识别合规性风险 (模拟 AGI 逻辑)
      let complianceStatus = 'PASS';
      let riskScore = 0;
      let failureReason = '';

      if (action === 'DELETE_ORDER') {
        complianceStatus = 'FAIL';
        riskScore = 95;
        failureReason = `Action ${action} on ${resourceId} by ${actorId} is not allowed by policy.`;
      } else if (action === 'FORCE_REFUND') {
        complianceStatus = 'REVIEW';
        riskScore = 50;
        failureReason = `Forced refund by ${actorId} needs additional approval.`;
      }

      const log = {
        id: `CG-${tenantId}-${id}`,
        tenantId,
        auditLogId: id,
        action,
        complianceStatus,
        riskScore,
        failureReason,
        created_at: new Date()
      };

      auditResults.push(log);

      // 3. 存储合规记录
      await db(this.GUARD_TABLE)
        .insert(log)
        .onConflict(['id'])
        .merge();
    }

    return auditResults;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.GUARD_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.GUARD_TABLE} table...`);
      await db.schema.createTable(this.GUARD_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('auditLogId', 64).notNullable();
        table.string('action', 64).notNullable();
        table.string('complianceStatus', 20); // E.g., PASS, FAIL, REVIEW
        table.integer('riskScore'); // 0-100
        table.text('failureReason');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'complianceStatus']);
      });
    }
  }
}
