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

export interface SupplierScore {
  supplierId: string;
  tenantId: string;
  overallScore: number; // 0-100
  deliverySpeedScore: number;
  qualityScore: number;
  priceCompetitivenessScore: number;
  afterSalesScore: number;
  lastEvaluatedAt: Date;
}

/**
 * [BIZ_SC_13] 供应商绩效自动评分模型 (Supplier Scoring Model)
 * @description 核心逻辑：基于历史采购订单、到货时效、质检结果与售后率自动计算供应商综合评分。
 */
export class SupplierScoringService {
  private static readonly SCORE_TABLE = 'cf_supplier_scores';

  /**
   * 执行供应商评估
   */
  static async evaluateSupplier(supplierId: string, tenantId: string): Promise<SupplierScore> {
    logger.info(`[SCM] Evaluating supplier ${supplierId} for Tenant ${tenantId}`);

    // 1. 获取供应商的历史采购数据
    const poStats = await db('cf_purchase_orders')
      .where({ supplier_id: supplierId, tenant_id: tenantId })
      .select(
        db.raw('AVG(DATEDIFF(updated_at, created_at)) as avgDeliveryDays'),
        db.raw('COUNT(*) as totalOrders'),
        db.raw('SUM(CASE WHEN status = "STOCKED" THEN 1 ELSE 0 END) as successfulOrders')
      )
      .first();

    // 2. 获取质检数据 (Mock 逻辑，实际应联动 QA 表)
    const qaPassRate = (Number(poStats.successfulOrders) / Number(poStats.totalOrders)) || 0.95;

    // 3. 计算各维度分数 (0-100)
    const avgDays = Number(poStats.avgDeliveryDays) || 5;
    const deliveryScore = Math.max(0, 100 - (avgDays - 3) * 10);
    const qualityScore = qaPassRate * 100;
    const priceScore = 85; // 暂定基础分
    const afterSalesScore = 90; // 暂定基础分

    // 4. 计算综合评分 (加权平均)
    const overallScore = (
      deliveryScore * 0.3 +
      qualityScore * 0.4 +
      priceScore * 0.2 +
      afterSalesScore * 0.1
    );

    const score: SupplierScore = {
      supplierId,
      tenantId,
      overallScore: Number(overallScore.toFixed(2)),
      deliverySpeedScore: Number(deliveryScore.toFixed(2)),
      qualityScore: Number(qualityScore.toFixed(2)),
      priceCompetitivenessScore: Number(priceScore.toFixed(2)),
      afterSalesScore: Number(afterSalesScore.toFixed(2)),
      lastEvaluatedAt: new Date()
    };

    // 5. 保存到数据库
    await db(this.SCORE_TABLE)
      .insert({
        ...score,
        created_at: new Date(),
        updated_at: new Date()
      })
      .onConflict(['supplierId', 'tenantId'])
      .merge();

    return score;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const exists = await db.schema.hasTable(this.SCORE_TABLE);
    if (!exists) {
      logger.info(`📦 Creating ${this.SCORE_TABLE} table...`);
      await db.schema.createTable(this.SCORE_TABLE, (table) => {
        table.string('supplierId', 64).notNullable();
        table.string('tenantId', 64).notNullable();
        table.decimal('overallScore', 5, 2);
        table.decimal('deliverySpeedScore', 5, 2);
        table.decimal('qualityScore', 5, 2);
        table.decimal('priceCompetitivenessScore', 5, 2);
        table.decimal('afterSalesScore', 5, 2);
        table.timestamp('lastEvaluatedAt');
        table.timestamps(true, true);

        table.primary(['supplierId', 'tenantId']);
      });
    }
  }
}
