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

/**
 * [BIZ_FIN_198] 基于用户行为特征的恶意索赔拦截建议 (Claim)
 * @description 识别恶意索赔，保护商户利益。
 */
export class ClaimFraudService {
  private static readonly FRAUD_TABLE = 'cf_claim_fraud_detections';

  /**
   * 识别恶意索赔
   */
  static async detectClaimFraud(tenantId: string, customerId: string, claimId: string) {
    logger.info(`[ClaimFraud] Detecting fraud for claim: ${claimId} for customer: ${customerId} for tenant: ${tenantId}`);

    // 1. 获取用户历史索赔记录
    const stats = await db('cf_claims')
      .where({ customer_id: customerId, tenant_id: tenantId })
      .select(
        db.raw('COUNT(id) as totalClaims'),
        db.raw('SUM(CASE WHEN status = "APPROVED" THEN 1 ELSE 0 END) as approvedClaims')
      );

    const totalClaims = Number(stats[0].totalClaims || 0);
    const approvedClaims = Number(stats[0].approvedClaims || 0);

    // 2. 评估欺诈风险 (如果总索赔数 > 3 且索赔/订单比率 > 0.5)
    const customerOrders = await db('cf_consumer_orders')
      .where({ customer_id: customerId, tenant_id: tenantId })
      .select(db.raw('COUNT(id) as totalOrders'));

    const totalOrders = Number(customerOrders[0].totalOrders || 1);
    const claimToOrderRatio = totalClaims / totalOrders;

    let riskLevel = 'LOW';
    let suggestion = 'PROCEED_WITH_CLAIM';
    let reason = 'Normal customer behavior';

    if (totalClaims > 3 && claimToOrderRatio > 0.5) {
      riskLevel = 'HIGH';
      suggestion = 'BLOCK_AND_INVESTIGATE';
      reason = `Customer has high claim-to-order ratio (${(claimToOrderRatio * 100).toFixed(0)}%). Possible malicious behavior.`;
    } else if (totalClaims > 2) {
      riskLevel = 'MEDIUM';
      suggestion = 'MANUAL_REVIEW';
      reason = `Customer has multiple claims (${totalClaims}). Review history before approving.`;
    }

    const detectionRecord = {
      id: `FD-${tenantId}-${customerId}-${claimId}`,
      tenantId,
      customerId,
      claimId,
      totalClaims,
      totalOrders,
      claimToOrderRatio: Number(claimToOrderRatio.toFixed(4)),
      riskLevel,
      suggestion,
      reason,
      created_at: new Date()
    };

    // 3. 存储欺诈检测记录
    await db(this.FRAUD_TABLE)
      .insert(detectionRecord)
      .onConflict(['id'])
      .merge();

    return detectionRecord;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.FRAUD_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.FRAUD_TABLE} table...`);
      await db.schema.createTable(this.FRAUD_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('customerId', 128).notNullable();
        table.string('claimId', 128).notNullable();
        table.integer('totalClaims');
        table.integer('totalOrders');
        table.decimal('claimToOrderRatio', 5, 4);
        table.string('riskLevel', 20); // E.g., LOW, MEDIUM, HIGH
        table.string('suggestion', 32); // E.g., PROCEED_WITH_CLAIM, BLOCK_AND_INVESTIGATE, MANUAL_REVIEW
        table.text('reason');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'customerId']);
      });
    }
  }
}
