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

/**
 * [BIZ_FIN_171] 多平台回款周期差异导致的杠杆风险 (Leverage)
 * @description 评估回款周期对现金流的影响，预警杠杆风险。
 */
export class PayoutCycleService {
  private static readonly CYCLE_RISK_TABLE = 'cf_payout_cycle_risks';

  /**
   * 评估指定租户的回款周期风险
   */
  static async auditTenantPayoutRisk(tenantId: string) {
    logger.info(`[PayoutCycle] Auditing payout cycle risk for tenant: ${tenantId}`);

    // 1. 获取过去 90 天的平台订单与回款数据
    const platforms = ['AMAZON', 'ALIEXPRESS', 'TEMU', 'TIKTOK'];
    const risks = [];

    for (const platform of platforms) {
      // 计算订单创建日期与实际回款日期之间的平均差异 (回款周期)
      const query = await db('cf_consumer_orders')
        .join('cf_transactions', 'cf_consumer_orders.id', '=', 'cf_transactions.order_id')
        .where('cf_consumer_orders.tenant_id', tenantId)
        .andWhere('cf_consumer_orders.platform', platform)
        .andWhere('cf_transactions.transaction_type', 'PAYOUT')
        .andWhere('cf_consumer_orders.created_at', '>=', new Date(Date.now() - 90 * 24 * 60 * 60 * 1000))
        .select(
          db.raw('AVG(DATEDIFF(cf_transactions.created_at, cf_consumer_orders.created_at)) as avgCycleDays'),
          db.raw('SUM(cf_consumer_orders.total_amount) as platformSales')
        );

      const result = query[0];
      const avgCycleDays = Number(result.avgCycleDays || 0);
      const platformSales = Number(result.platformSales || 0);

      // 2. 评估风险级别
      let riskLevel = 'LOW';
      let recommendation = 'Monitor regularly';

      if (avgCycleDays > 30) {
        riskLevel = 'HIGH';
        recommendation = 'Reduce inventory buffer or seek short-term financing';
      } else if (avgCycleDays > 14) {
        riskLevel = 'MEDIUM';
        recommendation = 'Optimize shipping speed to trigger earlier payout';
      }

      const riskRecord = {
        id: `PR-${tenantId}-${platform}-${new Date().toISOString().split('T')[0]}`,
        tenantId,
        platform,
        avgCycleDays,
        platformSales,
        riskLevel,
        recommendation,
        created_at: new Date()
      };

      risks.push(riskRecord);

      // 3. 存储风险记录
      await db(this.CYCLE_RISK_TABLE)
        .insert(riskRecord)
        .onConflict(['id'])
        .merge();
    }

    return risks;
  }

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