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

export interface CommodityPosition {
  id: string;
  tenantId: string;
  commodityType: 'OIL' | 'GOLD' | 'STEEL' | 'COPPER';
  quantity: number;
  entryPrice: number;
  currentMarketPrice: number;
  hedgedPercentage: number; // 0-1
}

export interface HedgingAdvice {
  positionId: string;
  action: 'BUY_FUTURE' | 'SELL_PUT' | 'HOLD';
  confidence: number;
  reasoning: string;
}

/**
 * [BIZ_FIN_14] 跨租户大宗商品价格对冲对账 (Commodity Hedging)
 * @description 为涉及大宗原材料采购的跨境租户提供实时的价格波动风险评估、对冲策略建议与跨租户财务对账逻辑。
 */
export class CommodityHedgingService {
  /**
   * 评估商品价格风险
   */
  static async evaluateRisk(tenantId: string, commodity: string): Promise<HedgingAdvice> {
    logger.info(`[CommodityHedging] Evaluating risk for tenant: ${tenantId}, commodity: ${commodity}`);

    // 1. 获取实时市场价格 (模拟)
    const marketPrice = 1500.0 + Math.random() * 100.0;

    // 2. 模拟对冲算法决策
    // 逻辑：如果当前价格高于历史平均值 10%，建议购买看跌期权
    const advice: HedgingAdvice = {
      positionId: `pos-${Date.now()}`,
      action: marketPrice > 1550 ? 'SELL_PUT' : 'BUY_FUTURE',
      confidence: 0.88,
      reasoning: `Market volatility detected for ${commodity}. Current price ${marketPrice} is trending upwards.`
    };

    return advice;
  }

  /**
   * 执行跨租户大宗对账
   * @param sourceTenant 供应商租户
   * @param targetTenant 采购商租户
   * @param amount 结算金额
   */
  static async performCrossTenantRecon(sourceTenant: string, targetTenant: string, amount: number): Promise<{
    reconId: string;
    status: 'MATCHED' | 'DISCREPANCY';
    difference?: number;
  }> {
    logger.info(`[CommodityHedging] Running cross-tenant recon between ${sourceTenant} and ${targetTenant}`);

    // 1. 获取双方合约数据
    const sourceContract = await db('cf_commodity_contracts')
      .where({ tenantId: sourceTenant, status: 'ACTIVE' })
      .first();
    const targetContract = await db('cf_commodity_contracts')
      .where({ tenantId: targetTenant, status: 'ACTIVE' })
      .first();

    // 2. 三流合一校验逻辑 (订单流、物流、资金流)
    // 这里模拟：如果双方锁定的价格偏差超过 2%，标记异常
    let status: 'MATCHED' | 'DISCREPANCY' = 'MATCHED';
    let difference = 0;

    if (sourceContract && targetContract) {
      const priceDiff = Math.abs(sourceContract.lockedPrice - targetContract.lockedPrice);
      if (priceDiff / sourceContract.lockedPrice > 0.02) {
        status = 'DISCREPANCY';
        difference = priceDiff;
      }
    }

    const reconId = `HED-REC-${Date.now()}`;
    
    // 3. 记录对账结果 (假设有 cf_hedging_recons 表)
    // await db('cf_hedging_recons').insert({ ... });

    return {
      reconId,
      status,
      difference
    };
  }

  /**
   * 自动平仓建议触发
   */
  static async triggerAutoClose(positionId: string) {
    logger.warn(`[CommodityHedging] Triggering auto-close for position: ${positionId} due to stop-loss threshold.`);
    
    // 1. 更新合约状态
    await db('cf_commodity_contracts')
      .where({ id: positionId })
      .update({
        status: 'CLOSED',
        updated_at: new Date()
      });

    // 2. 发起金融交易平仓指令 (联动外部 Bridge)
    logger.info(`[CommodityHedging] Financial close instruction sent for ${positionId}`);
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable('cf_commodity_contracts');
    if (!hasTable) {
      logger.info('📦 Creating cf_commodity_contracts table...');
      await db.schema.createTable('cf_commodity_contracts', (table) => {
        table.string('id', 64).primary();
        table.string('commodityType', 50).notNullable();
        table.float('lockedPrice');
        table.string('currency', 10).defaultTo('USD');
        table.timestamp('expiryDate');
        table.string('status', 20).defaultTo('ACTIVE');
        table.timestamps(true, true);
        table.index(['commodityType', 'status']);
      });
    }
  }
}
