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

export interface ComplianceViolation {
  tenantId: string;
  dataType: 'PII' | 'FINANCIAL' | 'HEALTH' | 'LOCATION';
  sourceRegion: string;
  targetRegion: string;
  violationType: 'UNAUTHORIZED_CROSS_BORDER' | 'ENCRYPTION_MISSING' | 'RETENTION_EXCEEDED';
  evidence: string;
}

/**
 * [BIZ_AUDIT_13] 跨区域数据流动合规性实时检测 (GDPR/CCPA Scan)
 * @description 核心逻辑：监控租户数据的存储位置与流动路径，实时检测是否违反 GDPR（欧盟）、
 * CCPA（加州）或其他地区的跨境数据流动合规要求。自动识别未加密敏感信息并触发拦截或脱敏。
 */
export class DataComplianceService {
  private static readonly VIOLATION_TABLE = 'cf_compliance_violations';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.VIOLATION_TABLE);
    if (!hasTable) {
      logger.info('📦 Creating cf_compliance_violations table...');
      await db.schema.createTable(this.VIOLATION_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('data_type', 32).notNullable();
        table.string('source_region', 16);
        table.string('target_region', 16);
        table.string('violation_type', 64).notNullable();
        table.text('evidence');
        table.string('status', 16).defaultTo('DETECTED'); // DETECTED, RESOLVED, IGNORED
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }

  /**
   * 执行数据流动合规性扫描
   */
  static async scanDataFlow(params: {
    tenantId: string;
    payload: any;
    sourceRegion: string;
    targetRegion: string;
  }): Promise<{ isCompliant: boolean; risks: string[] }> {
    const { tenantId, payload, sourceRegion, targetRegion } = params;

    // 1. 全局开关检查
    if (!(await FeatureGovernanceService.isEnabled('BIZ_AUDIT_DATA_COMPLIANCE', tenantId))) {
      return { isCompliant: true, risks: [] };
    }

    const risks: string[] = [];

    // 2. 模拟 GDPR 规则检查 (EU -> Non-EU)
    if (sourceRegion === 'EU' && !['EU', 'US'].includes(targetRegion)) {
      risks.push('GDPR violation: Sensitive data moving from EU to non-adequacy region.');
    }

    // 3. 模拟敏感字段扫描 (Regex based PII detection)
    const payloadStr = JSON.stringify(payload);
    const emailPattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
    if (emailPattern.test(payloadStr) && targetRegion !== sourceRegion) {
      risks.push('PII leakage: Unmasked email detected in cross-border flow.');
    }

    // 4. 记录违规
    if (risks.length > 0) {
      await db(this.VIOLATION_TABLE).insert({
        tenant_id: tenantId,
        data_type: 'PII',
        source_region: sourceRegion,
        target_region: targetRegion,
        violation_type: 'UNAUTHORIZED_CROSS_BORDER',
        evidence: risks.join('; ')
      });
      logger.error(`[Compliance] Violation detected for Tenant ${tenantId}: ${risks[0]}`);
    }

    return {
      isCompliant: risks.length === 0,
      risks
    };
  }

  /**
   * 获取租户合规性报告
   */
  static async getComplianceReport(tenantId: string) {
    return await db(this.VIOLATION_TABLE)
      .where({ tenant_id: tenantId })
      .orderBy('created_at', 'desc');
  }
}
