import db from '../config/database';
import { AuditService } from './AuditService';

/**
 * [BIZ_FIN_14] 跨租户大宗商品价格对冲对账
 * 负责管理原材料（如塑料、纸张等）的价格对冲，降低供应链成本波动
 */
export class CommodityHedgingService {
  /**
   * 创建对冲头寸
   */
  static async createHedgingPosition(
    tenantId: string,
    commodityType: string,
    quantity: number,
    strikePrice: number,
    expiryDate: Date,
    traceId: string
  ) {
    const [id] = await db('cf_commodity_hedging').insert({
      tenant_id: tenantId,
      commodity_type: commodityType,
      hedged_quantity: quantity,
      strike_price: strikePrice,
      expiry_date: expiryDate,
      status: 'ACTIVE'
    });

    await AuditService.log({
      tenantId: tenantId,
      userId: 'SYSTEM',
      module: 'COMMODITY',
      action: 'CREATE_COMMODITY_HEDGING',
      resourceType: 'COMMODITY_HEDGING',
      resourceId: id.toString(),
      traceId: traceId,
      afterSnapshot: JSON.stringify({ commodityType, quantity, strikePrice, expiryDate }),
      result: 'success',
      source: 'node',
      metadata: { reason: 'Price volatility protection' }
    });

    return id;
  }

  /**
   * 对账并结算对冲收益/亏损
   */
  static async reconcileAndSettle(
    tenantId: string,
    positionId: number,
    currentMarketPrice: number,
    traceId: string
  ) {
    const position = await db('cf_commodity_hedging')
      .where({ id: positionId, tenant_id: tenantId })
      .first();

    if (!position || position.status !== 'ACTIVE') {
      throw new Error('Position not found or already settled');
    }

    // 计算收益/亏损: (行权价 - 市场价) * 数量 (假设是看跌保护)
    // 或者反之。这里简化逻辑：如果市场价高于行权价，对冲产生正向价值（锁定低价）
    const pnl = (currentMarketPrice - position.strike_price) * position.hedged_quantity;

    await db.transaction(async (trx) => {
      await trx('cf_commodity_hedging')
        .where({ id: positionId })
        .update({
          status: 'EXECUTED',
          updated_at: db.fn.now()
        });

      // 记录对账结果
      await AuditService.log({
        tenantId: tenantId,
        userId: 'SYSTEM',
        module: 'COMMODITY',
        action: 'SETTLE_COMMODITY_HEDGING',
        resourceType: 'COMMODITY_HEDGING',
        resourceId: positionId.toString(),
        traceId: traceId,
        afterSnapshot: JSON.stringify({ currentMarketPrice, pnl }),
        result: 'success',
        source: 'node',
        metadata: { strikePrice: position.strike_price }
      });
    });

    return pnl;
  }

  /**
   * 获取租户所有活动中的对冲头寸
   */
  static async getActivePositions(tenantId: string) {
    return await db('cf_commodity_hedging')
      .where({ tenant_id: tenantId, status: 'ACTIVE' })
      .orderBy('expiry_date', 'asc');
  }
}
