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

export interface SupplierRiskAssessment {
  tenantId: string;
  supplierId: string;
  financialStability: number; // 0-100
  complianceScore: number; // 0-100
  geopoliticalRisk: number; // 0-100
}

/**
 * [BIZ_SC_14] 供应商风险雷达与动态准入控制服务
 * @description 结合财务、合规与地缘政治因素，实时监控供应商风险并自动拦截高风险操作
 */
export class SupplierRiskRadarService {
  private static readonly TABLE_NAME = 'cf_supplier_risk';

  /**
   * 执行供应商风险评估 (BIZ_SC_14)
   */
  static async performAssessment(params: SupplierRiskAssessment): Promise<void> {
    logger.info(`[RiskRadar] Assessing risk for Supplier: ${params.supplierId}`);

    // 1. 计算综合风险分
    const riskScore = (params.financialStability * 0.3) + (params.complianceScore * 0.4) + (params.geopoliticalRisk * 0.3);
    let riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL' = 'LOW';

    if (riskScore > 80) riskLevel = 'CRITICAL';
    else if (riskScore > 60) riskLevel = 'HIGH';
    else if (riskScore > 30) riskLevel = 'MEDIUM';

    // 2. 持久化风险画像
    await db(this.TABLE_NAME)
      .insert({
        tenant_id: params.tenantId,
        supplier_id: params.supplierId,
        risk_score: riskScore,
        risk_level: riskLevel,
        risk_factors: `Financial: ${params.financialStability}, Compliance: ${params.complianceScore}, Geo: ${params.geopoliticalRisk}`,
        last_audited_at: new Date(),
        created_at: new Date(),
        updated_at: new Date()
      })
      .onConflict(['tenant_id', 'supplier_id'])
      .merge();

    // 3. 触发自动化动作
    if (riskLevel === 'CRITICAL' || riskLevel === 'HIGH') {
      await this.handleHighRiskSupplier(params.tenantId, params.supplierId, riskLevel, riskScore);
    }
  }

  /**
   * 高风险供应商自动化处理 (BIZ_SC_14)
   */
  private static async handleHighRiskSupplier(tenantId: string, supplierId: string, level: string, score: number): Promise<void> {
    logger.error(`[RiskRadar] ALERT: High risk supplier detected: ${supplierId}, Level: ${level}, Score: ${score}`);

    // 自动触发策略建议 (BIZ_AI_16-EXT)
    await AdviceService.recordAdvice({
      tenantId,
      shopId: 'DEFAULT',
      traceId: `RISK-SUP-${Date.now()}`,
      insight: {
        type: 'ARBITRAGE',
        title: `Supplier Risk Alert: ${supplierId}`,
        description: `Supplier ${supplierId} reached ${level} risk level (Score: ${score}). Potential impact on supply chain stability.`,
        impact: 'high',
        confidence: 0.95,
        suggestedAction: 'Pause all purchase orders for this supplier and switch to backup alternatives.',
        metadata: { supplierId, riskLevel: level, riskScore: score }
      }
    });

    // 在实际业务中，此处可以调用 PurchaseService 自动锁定该供应商的所有待执行 PO
  }

  /**
   * 检查供应商是否允许下单 (动态准入控制)
   */
  static async isSupplierAllowed(tenantId: string, supplierId: string): Promise<boolean> {
    const risk = await db(this.TABLE_NAME).where({ tenant_id: tenantId, supplier_id: supplierId }).first();
    if (!risk) return true; // 未评估默认允许

    return risk.risk_level !== 'CRITICAL';
  }
}
