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

/**
 * [BIZ_FIN_194] 高频取消订单导致的支付网关风险预警 (Gateway)
 * @description 监控订单取消率，预警支付网关（PayPal/Stripe）风险。
 */
export class PaymentRiskService {
  private static readonly RISK_TABLE = 'cf_payment_gateway_risks';

  /**
   * 评估支付网关风险
   */
  static async auditGatewayRisk(tenantId: string) {
    logger.info(`[PaymentRisk] Auditing gateway risk for tenant: ${tenantId}`);

    // 1. 获取过去 30 天的订单总量和取消总量
    const stats = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId })
      .andWhere('created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .select(
        db.raw('COUNT(id) as totalOrders'),
        db.raw('SUM(CASE WHEN status = "CANCELED" THEN 1 ELSE 0 END) as canceledOrders')
      );

    const totalOrders = Number(stats[0].totalOrders || 0);
    const canceledOrders = Number(stats[0].canceledOrders || 0);
    const cancellationRatio = totalOrders > 0 ? canceledOrders / totalOrders : 0;

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

    if (cancellationRatio > 0.2) {
      riskLevel = 'CRITICAL';
      recommendation = 'High cancellation rate detected (>20%). Gateway at risk of suspension. Audit cancellation reasons.';
    } else if (cancellationRatio > 0.1) {
      riskLevel = 'MEDIUM';
      recommendation = 'Cancellation rate is elevated (>10%). Monitor closely.';
    }

    const riskRecord = {
      id: `GR-${tenantId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      totalOrders,
      canceledOrders,
      cancellationRatio: Number(cancellationRatio.toFixed(4)),
      riskLevel,
      recommendation,
      created_at: new Date()
    };

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

    return riskRecord;
  }

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