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

/**
 * [BIZ_FIN_191] 跨国转让定价合规性建议 (Transfer Pricing)
 * @description 预防反避税调查，提供跨国转让定价合规建议。
 */
export class LegalTaxService {
  private static readonly COMPLIANCE_TABLE = 'cf_legal_tax_compliance';

  /**
   * 检查转让定价合规性
   */
  static async checkTransferPricingCompliance(tenantId: string) {
    logger.info(`[LegalTax] Checking transfer pricing compliance for tenant: ${tenantId}`);

    // 1. 获取不同主体间的交易额 (基于订单目的地)
    const stats = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId })
      .select(
        'destination_country',
        db.raw('SUM(total_amount) as totalSales'),
        db.raw('COUNT(id) as orderCount')
      )
      .groupBy('destination_country');

    const complianceResults = [];

    for (const stat of stats) {
      const { destination_country, totalSales, orderCount } = stat;
      
      // 2. 识别潜在风险 (跨国销售额 > $1M 或单个国家订单 > 10000)
      let riskLevel = 'LOW';
      let suggestion = 'Compliant with current volume';

      if (totalSales > 1000000 || orderCount > 10000) {
        riskLevel = 'HIGH';
        suggestion = 'High cross-border volume detected. Consult local tax advisor for transfer pricing audit.';
      } else if (totalSales > 500000) {
        riskLevel = 'MEDIUM';
        suggestion = 'Monitor cross-border sales closely. Prepare documentation for tax audit.';
      }

      const report = {
        id: `LT-${tenantId}-${destination_country}-${new Date().toISOString().split('T')[0]}`,
        tenantId,
        country: destination_country,
        totalSales: Number(totalSales),
        orderCount: Number(orderCount),
        riskLevel,
        suggestion,
        created_at: new Date()
      };

      complianceResults.push(report);

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

    return complianceResults;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.COMPLIANCE_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.COMPLIANCE_TABLE} table...`);
      await db.schema.createTable(this.COMPLIANCE_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('country', 64).notNullable();
        table.decimal('totalSales', 15, 2);
        table.integer('orderCount');
        table.string('riskLevel', 20); // E.g., LOW, MEDIUM, HIGH
        table.text('suggestion');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'country']);
      });
    }
  }
}
