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

/**
 * [BIZ_SOV_13] 声誉驱动的阶梯费率与流量倾斜 (Reputation Perks)
 * @description 根据节点声誉自动调整费率与流量分配权重。
 */
export class ReputationPerksService {
  private static readonly PERKS_TABLE = 'cf_reputation_perks';

  /**
   * 根据声誉分计算费率折扣
   * @param reputationScore 声誉分 (0-100)
   */
  static calculateRateDiscount(reputationScore: number): number {
    if (reputationScore >= 90) return 0.20; // 90分以上，8折
    if (reputationScore >= 80) return 0.10; // 80分以上，9折
    if (reputationScore >= 70) return 0.05; // 70分以上，95折
    return 0;
  }

  /**
   * 根据声誉分计算流量权重
   * @param reputationScore 声誉分 (0-100)
   */
  static calculateTrafficWeight(reputationScore: number): number {
    if (reputationScore >= 90) return 1.5; // 1.5倍权重
    if (reputationScore >= 80) return 1.2; // 1.2倍权重
    return 1.0;
  }

  /**
   * 记录声誉权益应用日志
   */
  static async applyPerks(tenantId: string, nodeId: string, score: number) {
    const discount = this.calculateRateDiscount(score);
    const weight = this.calculateTrafficWeight(score);

    logger.info(`[ReputationPerks] Applying perks for node ${nodeId}: Discount=${discount}, Weight=${weight}`);

    await db(this.PERKS_TABLE).insert({
      tenant_id: tenantId,
      node_id: nodeId,
      reputation_score: score,
      applied_discount: discount,
      applied_traffic_weight: weight,
      created_at: new Date()
    });

    return { discount, weight };
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.PERKS_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.PERKS_TABLE} table...`);
      await db.schema.createTable(this.PERKS_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('node_id', 128).notNullable().index();
        table.decimal('reputation_score', 5, 2);
        table.decimal('applied_discount', 5, 4);
        table.decimal('applied_traffic_weight', 5, 2);
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }
}
