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

/**
 * [BIZ_FIN_173] 高额退款导致的资金链冻结预警 (Freeze)
 * @description 监控退款比例，评估资金链风险，预警高额退款导致的资金冻结。
 */
export class RefundRiskService {
  private static readonly RISK_TABLE = 'cf_refund_risks';

  /**
   * 评估租户退款风险
   */
  static async auditTenantRefundRisk(tenantId: string) {
    logger.info(`[RefundRisk] Auditing refund risk for tenant: ${tenantId}`);

    // 1. 获取过去 30 天的订单与退款数据
    const result = await db('cf_consumer_orders')
      .where('tenant_id', tenantId)
      .andWhere('created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .select(
        db.raw('SUM(total_amount) as totalSales'),
        db.raw('COUNT(id) as orderCount')
      );

    const refunds = await db('cf_transactions')
      .where('tenant_id', tenantId)
      .andWhere('transaction_type', 'REFUND')
      .andWhere('created_at', '>=', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000))
      .select(
        db.raw('SUM(amount) as totalRefunds'),
        db.raw('COUNT(id) as refundCount')
      );

    const totalSales = Number(result[0].totalSales || 0);
    const orderCount = Number(result[0].orderCount || 0);
    const totalRefunds = Math.abs(Number(refunds[0].totalRefunds || 0));
    const refundCount = Number(refunds[0].refundCount || 0);

    // 2. 评估风险级别
    const refundRatio = totalSales > 0 ? totalRefunds / totalSales : 0;
    let riskLevel = 'LOW';
    let recommendation = 'Normal operations';

    if (refundRatio > 0.15) {
      riskLevel = 'CRITICAL';
      recommendation = 'Immediate investigation of product quality and logistics. Prepare cash reserve.';
    } else if (refundRatio > 0.05) {
      riskLevel = 'MEDIUM';
      recommendation = 'Monitor refund trends and customer feedback.';
    }

    const riskRecord = {
      id: `RR-${tenantId}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      totalSales,
      orderCount,
      totalRefunds,
      refundCount,
      refundRatio: Number(refundRatio.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.decimal('totalSales', 15, 2);
        table.integer('orderCount');
        table.decimal('totalRefunds', 15, 2);
        table.integer('refundCount');
        table.decimal('refundRatio', 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']);
      });
    }
  }
}
