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

export interface DataComplianceRecord {
  tenantId: string;
  sourceRegion: string;
  targetRegion: string;
  dataType: 'SENSITIVE' | 'ORDER' | 'FINANCIAL' | 'LOGISTICS';
  isCompliant: boolean;
  reason?: string;
}

/**
 * [BIZ_AUDIT_DATA_COMPLIANCE] 跨区域数据流动合规性扫描 (Data Compliance Audit)
 * @description 核心逻辑：建立租户数据的主权标签，监控数据流向。
 * 基于 AGI 自动扫描跨国/跨区域的数据调用路径（如：从欧盟服务器拉取含 PII 信息的订单至非合规区域），
 * 识别违反 GDPR、PIPL 或特定贸易主权协议的行为。
 */
export class DataComplianceService {
  private static readonly LOG_TABLE = 'cf_data_compliance_logs';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.LOG_TABLE);
    if (!hasTable) {
      console.log(`📦 Creating ${this.LOG_TABLE} table...`);
      await db.schema.createTable(this.LOG_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('source_region', 32);
        table.string('target_region', 32);
        table.string('data_type', 32);
        table.boolean('is_compliant').defaultTo(true);
        table.text('reason');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
      console.log(`✅ Table ${this.LOG_TABLE} created`);
    }
  }

  /**
   * 检查数据流向合规性 (BIZ_AUDIT_DATA_COMPLIANCE)
   */
  static async auditDataFlow(record: DataComplianceRecord) {
    if (!(await FeatureGovernanceService.isEnabled('BIZ_AUDIT_DATA_COMPLIANCE', record.tenantId))) {
      return;
    }

    // 1. 合规性检测逻辑
    let isCompliant = true;
    let reason = '';

    // 模拟检测逻辑：从欧盟 (EU) 向非合规地区传输 PII 信息
    if (record.sourceRegion === 'EU' && record.targetRegion !== 'EU' && record.dataType === 'SENSITIVE') {
      isCompliant = false;
      reason = 'Cross-border transfer of sensitive PII from EU to non-compliant region detected.';
    }

    // 2. 记录审计结果
    await db(this.LOG_TABLE).insert({
      tenant_id: record.tenantId,
      source_region: record.sourceRegion,
      target_region: record.targetRegion,
      data_type: record.dataType,
      is_compliant: isCompliant,
      reason: reason || 'Compliant path'
    });

    if (!isCompliant) {
      logger.error(`[DataCompliance] Compliance violation detected for ${record.tenantId}: ${reason}`);
      // TODO: 联动告警系统
    }
  }
}
