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

export interface CourierScore {
  courier_did: string;
  rating: number; // 0-100
  successful_deliveries: number;
  dispute_count: number;
  last_updated: Date;
}

/**
 * [BIZ_LOG_70] 众包物流配送员 DID 信用分级体系 (Courier Credit)
 * @description 为众包配送员建立信用分，动态调整派单优先级。
 */
export class CourierCreditService {
  private static readonly CREDIT_TABLE = 'cf_courier_credits';

  /**
   * 更新配送员信用分
   */
  static async updateCourierScore(courierDid: string, metrics: { success: boolean; hasDispute: boolean }) {
    logger.info(`[CourierCredit] Updating score for courier: ${courierDid}`);

    // 1. 获取当前评分
    const current = await db(this.CREDIT_TABLE).where({ courier_did: courierDid }).first();
    
    let newScore = current ? Number(current.rating) : 80; // 初始分 80
    let deliveries = current ? current.successful_deliveries : 0;
    let disputes = current ? current.dispute_count : 0;

    // 2. 评分算法
    if (metrics.success) {
      newScore = Math.min(100, newScore + 0.5);
      deliveries += 1;
    } else {
      newScore = Math.max(0, newScore - 5);
    }

    if (metrics.hasDispute) {
      newScore = Math.max(0, newScore - 10);
      disputes += 1;
    }

    // 3. 更新数据库
    const record = {
      courier_did: courierDid,
      rating: Number(newScore.toFixed(2)),
      successful_deliveries: deliveries,
      dispute_count: disputes,
      last_updated: new Date()
    };

    await db(this.CREDIT_TABLE)
      .insert(record)
      .onConflict(['courier_did'])
      .merge();

    return record;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.CREDIT_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.CREDIT_TABLE} table...`);
      await db.schema.createTable(this.CREDIT_TABLE, (table) => {
        table.string('courier_did', 128).primary();
        table.decimal('rating', 5, 2).defaultTo(80.00);
        table.integer('successful_deliveries').defaultTo(0);
        table.integer('dispute_count').defaultTo(0);
        table.timestamp('last_updated').defaultTo(db.fn.now());
      });
    }
  }
}
