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

export interface ComplianceCheckResult {
  is_compliant: boolean;
  risk_score: number; // 0-100
  violations: string[];
  restricted_countries: string[];
  suggested_action: 'PROCEED' | 'BLOCK' | 'MANUAL_REVIEW';
}

/**
 * [BIZ_TRADE_40] AGI 驱动的全球合规与制裁扫描 (Compliance Scan)
 * @description 自动扫描 SKU 与收货地址，防止违反特定国家/地区的贸易禁令或合规风险。
 */
export class TradeComplianceService {
  private static readonly SCAN_LOG_TABLE = 'cf_compliance_scan_logs';
  private static readonly RULES_TABLE = 'cf_compliance_rules';

  /**
   * 执行全球合规扫描
   */
  static async scanOrder(tenantId: string, orderId: string): Promise<ComplianceCheckResult> {
    logger.info(`[TradeCompliance] Scanning order ${orderId} for tenant ${tenantId}`);

    const order = await db('cf_consumer_orders').where({ tenant_id: tenantId, order_id: orderId }).first();
    if (!order) {
      throw new Error(`Order ${orderId} not found`);
    }

    // 1. 获取目标国家与商品类别
    const destination = order.destination_country;
    const items = await db('cf_order_items').where({ order_id: orderId });

    // 2. 匹配合规规则 (模拟从数据库或第三方 API 获取)
    const violations: string[] = [];
    let riskScore = 0;

    // 模拟制裁名单检查 (e.g., OFAC)
    const restrictedCountries = ['IR', 'KP', 'SY', 'CU']; // 模拟限制国家
    if (restrictedCountries.includes(destination)) {
      violations.push(`Destination country ${destination} is under trade sanctions.`);
      riskScore += 90;
    }

    // 模拟出口管制检查 (e.g., 高科技、双用途商品)
    for (const item of items) {
      if (item.category === 'HIGH_TECH_ELECTRONICS' && destination === 'RU') {
        violations.push(`Item ${item.sku} (Category: ${item.category}) is restricted for export to RU.`);
        riskScore += 70;
      }
    }

    const isCompliant = riskScore < 50;
    const suggestedAction = riskScore >= 80 ? 'BLOCK' : (riskScore >= 50 ? 'MANUAL_REVIEW' : 'PROCEED');

    const result: ComplianceCheckResult = {
      is_compliant: isCompliant,
      risk_score: riskScore,
      violations,
      restricted_countries: restrictedCountries,
      suggested_action: suggestedAction
    };

    // 3. 记录扫描日志
    await db(this.SCAN_LOG_TABLE).insert({
      tenant_id: tenantId,
      order_id: orderId,
      risk_score: riskScore,
      is_compliant: isCompliant ? 1 : 0,
      suggested_action: suggestedAction,
      violations_json: JSON.stringify(violations),
      created_at: new Date()
    });

    return result;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasLogTable = await db.schema.hasTable(this.SCAN_LOG_TABLE);
    if (!hasLogTable) {
      logger.info(`📦 Creating ${this.SCAN_LOG_TABLE} table...`);
      await db.schema.createTable(this.SCAN_LOG_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('order_id', 64).notNullable().index();
        table.integer('risk_score').defaultTo(0);
        table.boolean('is_compliant').defaultTo(true);
        table.string('suggested_action', 32);
        table.json('violations_json');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }

    const hasRulesTable = await db.schema.hasTable(this.RULES_TABLE);
    if (!hasRulesTable) {
      logger.info(`📦 Creating ${this.RULES_TABLE} table...`);
      await db.schema.createTable(this.RULES_TABLE, (table) => {
        table.increments('id').primary();
        table.string('country_code', 10).notNullable().index();
        table.string('category_restricted', 64);
        table.string('risk_level', 16).defaultTo('HIGH');
        table.text('description');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }
}
