import { logger } from '../utils/logger';

export interface QualityReport {
  supplierId: string;
  returnRate: number;
  defectRate: number;
  avgDeliveryDays: number;
  customerRating: number;
}

/**
 * [BIZ_AUTO_08] 自动化供应商黑名单与质量预警 (Supplier Blacklist)
 * @description 基于退货率、质检结果与多维评分自动执行供应商风控，支持自动拉黑与准入拦截
 */
export class SupplierBlacklistService {
  private static readonly BLACKLIST_THRESHOLD = {
    RETURN_RATE: 0.15, // 15% 退货率触发预警
    DEFECT_RATE: 0.05, // 5% 次品率直接拉黑
    RATING: 2.5       // 低于 2.5 分拉黑
  };

  /**
   * 评估供应商风险并执行动作
   */
  static async evaluateSupplier(report: QualityReport): Promise<{ action: 'KEEP' | 'WARN' | 'BLOCK'; reason?: string }> {
    logger.info(`[SupplierRisk] Evaluating supplier: ${report.supplierId}`);

    // 1. 检查次品率 (严重风控)
    if (report.defectRate > this.BLACKLIST_THRESHOLD.DEFECT_RATE) {
      logger.error(`[SupplierRisk] BLOCKING supplier ${report.supplierId} due to high defect rate: ${report.defectRate}`);
      return { action: 'BLOCK', reason: 'High Defect Rate' };
    }

    // 2. 检查评分
    if (report.customerRating < this.BLACKLIST_THRESHOLD.RATING) {
      logger.warn(`[SupplierRisk] BLOCKING supplier ${report.supplierId} due to low rating: ${report.customerRating}`);
      return { action: 'BLOCK', reason: 'Critical Low Rating' };
    }

    // 3. 检查退货率 (预警)
    if (report.returnRate > this.BLACKLIST_THRESHOLD.RETURN_RATE) {
      logger.warn(`[SupplierRisk] WARNING supplier ${report.supplierId} due to high return rate: ${report.returnRate}`);
      return { action: 'WARN', reason: 'Abnormal Return Rate' };
    }

    return { action: 'KEEP' };
  }

  /**
   * 准入拦截校验
   */
  static async isBlocked(supplierId: string): Promise<boolean> {
    // 实际应查询 Redis 或数据库黑名单表
    return false; // 模拟校验通过
  }
}
