import { OrderAggregate, OrderType, OrderStatus, TradeInfo } from '../aggregates/order.aggregate';
import { Money } from '../value-objects/money.vo';
import { v4 as uuidv4 } from 'uuid';

export interface MatchResult {
  buyOrder: OrderAggregate;
  sellOrder: OrderAggregate;
  trade: TradeInfo;
}

/**
 * 撮合引擎领域服务
 * 实现简单的价格优先、时间优先撮合逻辑
 */
export class MatchingEngineService {
  /**
   * 尝试撮合两个订单
   */
  match(buyOrder: OrderAggregate, sellOrder: OrderAggregate): MatchResult | null {
    if (!buyOrder.canMatch(sellOrder)) {
      return null;
    }

    // 确定成交价格（以挂单在先的价格为准，这里简化为卖方价格）
    const tradePrice = sellOrder.price;

    // 确定成交数量
    const tradeQuantity = buyOrder.remainingQuantity.isLessThan(sellOrder.remainingQuantity)
      ? buyOrder.remainingQuantity
      : sellOrder.remainingQuantity;

    // 计算成交金额
    const tradeAmount = tradeQuantity.multiply(tradePrice.value);

    const tradeNo = this.generateTradeNo();

    const buyerTrade: TradeInfo = {
      tradeNo,
      counterpartyOrderId: sellOrder.id || sellOrder.orderNo,
      counterpartySequence: sellOrder.accountSequence,
      price: tradePrice,
      quantity: tradeQuantity,
      amount: tradeAmount,
      createdAt: new Date(),
    };

    const sellerTrade: TradeInfo = {
      tradeNo,
      counterpartyOrderId: buyOrder.id || buyOrder.orderNo,
      counterpartySequence: buyOrder.accountSequence,
      price: tradePrice,
      quantity: tradeQuantity,
      amount: tradeAmount,
      createdAt: new Date(),
    };

    // 更新订单
    buyOrder.fill(buyerTrade);
    sellOrder.fill(sellerTrade);

    return {
      buyOrder,
      sellOrder,
      trade: buyerTrade,
    };
  }

  /**
   * 从订单簿中查找匹配的订单
   */
  findMatchingOrders(
    incomingOrder: OrderAggregate,
    orderBook: OrderAggregate[],
  ): MatchResult[] {
    const results: MatchResult[] = [];

    // 筛选可撮合的订单
    const matchableOrders = orderBook.filter((order) => {
      if (order.accountSequence === incomingOrder.accountSequence) return false;
      if (order.type === incomingOrder.type) return false;
      if (order.status !== OrderStatus.PENDING && order.status !== OrderStatus.PARTIAL) return false;
      return incomingOrder.canMatch(order);
    });

    // 按价格排序（买单降序，卖单升序）
    matchableOrders.sort((a, b) => {
      if (incomingOrder.type === OrderType.BUY) {
        // 买单进来，找卖单，价格低的优先
        return a.price.value.minus(b.price.value).toNumber();
      } else {
        // 卖单进来，找买单，价格高的优先
        return b.price.value.minus(a.price.value).toNumber();
      }
    });

    // 逐个撮合
    for (const order of matchableOrders) {
      if (incomingOrder.status === OrderStatus.FILLED) break;

      const result = this.match(
        incomingOrder.type === OrderType.BUY ? incomingOrder : order,
        incomingOrder.type === OrderType.SELL ? incomingOrder : order,
      );

      if (result) {
        results.push(result);
      }
    }

    return results;
  }

  private generateTradeNo(): string {
    const timestamp = Date.now().toString(36);
    const random = Math.random().toString(36).substring(2, 8);
    return `T${timestamp}${random}`.toUpperCase();
  }
}
