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

/**
 * [BIZ_FIN_182] 大宗商品价格波动对采购成本的影响预测 (Commodity)
 * @description 监控大宗商品价格，预判对采购成本的影响。
 */
export class MaterialRiskService {
  private static readonly RISK_TABLE = 'cf_material_risks';

  /**
   * 预测大宗商品风险
   */
  static async predictMaterialRisk(tenantId: string, materialName: string) {
    logger.info(`[MaterialRisk] Predicting risk for material: ${materialName} for tenant: ${tenantId}`);

    // 1. 获取大宗商品的历史价格数据 (模拟 API 调用)
    const trends = [
      { name: 'Copper', currentPrice: 8500, previousPrice: 8000, trend: 'UP' },
      { name: 'Steel', currentPrice: 600, previousPrice: 620, trend: 'DOWN' },
      { name: 'Oil', currentPrice: 75, previousPrice: 70, trend: 'UP' }
    ];

    const material = trends.find(t => t.name.toLowerCase() === materialName.toLowerCase());
    if (!material) return null;

    // 2. 评估风险级别
    const changeRatio = (material.currentPrice - material.previousPrice) / material.previousPrice;
    let riskLevel = 'LOW';
    let suggestion = 'Maintain current sourcing';

    if (changeRatio > 0.05) {
      riskLevel = 'HIGH';
      suggestion = 'Stock up now or hedge with futures to lock in costs.';
    } else if (changeRatio > 0.02) {
      riskLevel = 'MEDIUM';
      suggestion = 'Monitor price closely and consider alternative materials.';
    }

    const riskRecord = {
      id: `MR-${tenantId}-${materialName}-${new Date().toISOString().split('T')[0]}`,
      tenantId,
      materialName,
      currentPrice: material.currentPrice,
      changeRatio: Number(changeRatio.toFixed(4)),
      riskLevel,
      suggestion,
      created_at: new Date()
    };

    // 3. 存储风险记录
    await db(this.RISK_TABLE)
      .insert(riskRecord)
      .onConflict(['id'])
      .merge();

    return riskRecord;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.RISK_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.RISK_TABLE} table...`);
      await db.schema.createTable(this.RISK_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenantId', 64).notNullable();
        table.string('materialName', 64).notNullable();
        table.decimal('currentPrice', 15, 2);
        table.decimal('changeRatio', 5, 4);
        table.string('riskLevel', 20);
        table.text('suggestion');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenantId', 'materialName']);
      });
    }
  }
}
