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

/**
 * [BIZ_FIN_166] 各国 VAT 税务起征点自动提醒建议 (VAT)
 * @description 监控销售额，提醒各国 VAT 起征点。
 */
export class TaxComplianceService {
  private static readonly MONITOR_TABLE = 'cf_vat_threshold_monitors';

  /**
   * 监控 VAT 起征点
   */
  static async monitorVATThresholds(tenantId: string) {
    logger.info(`[TaxCompliance] Monitoring VAT thresholds for tenant: ${tenantId}`);

    // 1. 获取各国的年度销售额
    const yearStart = new Date(new Date().getFullYear(), 0, 1);

    const stats = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId })
      .andWhere('created_at', '>=', yearStart)
      .select('destination_country', db.raw('SUM(total_amount) as annualSales'))
      .groupBy('destination_country');

    // 2. 各国起征点 (模拟)
    const thresholds: Record<string, number> = {
      'UK': 85000,
      'DE': 10000,
      'FR': 35000,
      'US': 100000
    };

    const alerts = [];

    for (const stat of stats) {
      const { destination_country, annualSales } = stat;
      const threshold = thresholds[destination_country] || 10000; // 默认 10k

      const usageRatio = Number(annualSales) / threshold;
      let status = 'SAFE';
      let alertMsg = 'Sales are well below VAT threshold';

      if (usageRatio > 0.9) {
        status = 'CRITICAL';
        alertMsg = `Sales in ${destination_country} reached ${(usageRatio * 100).toFixed(2)}% of VAT threshold. Register immediately!`;
      } else if (usageRatio > 0.7) {
        status = 'WARNING';
        alertMsg = `Sales in ${destination_country} reached ${(usageRatio * 100).toFixed(2)}% of VAT threshold. Prepare for registration.`;
      }

      const alert = {
        id: `VT-${tenantId}-${destination_country}-${new Date().getFullYear()}`,
        tenantId,
        country: destination_country,
        annualSales: Number(annualSales),
        threshold,
        usageRatio: Number(usageRatio.toFixed(4)),
        status,
        alertMsg,
        created_at: new Date()
      };

      alerts.push(alert);

      // 3. 存储提醒
      await db(this.MONITOR_TABLE)
        .insert(alert)
        .onConflict(['id'])
        .merge();
    }

    return alerts;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.MONITOR_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.MONITOR_TABLE} table...`);
      await db.schema.createTable(this.MONITOR_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('country', 64).notNullable();
        table.decimal('annualSales', 15, 2);
        table.decimal('threshold', 15, 2);
        table.decimal('usageRatio', 5, 4);
        table.string('status', 20); // E.g., SAFE, WARNING, CRITICAL
        table.text('alertMsg');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'country']);
      });
    }
  }
}
