package com.spot.config;

import com.spot.dto.mq.TradeResult;
import com.spot.entity.ExOrder;
import com.spot.enums.OrderStatus;
import com.spot.service.NewMatchingEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 撮合引擎 - 使用新匹配引擎处理订单
 *
 * @author jean
 * @date 2026-05-07
 */
@Component
@Slf4j
public class MatchingEngine {

    @Autowired
    private NewMatchingEngine newMatchingEngine;

    /**
     * 处理新进入的 init 状态订单（状态0）
     *
     * @param newOrder 新订单
     * @return 撮合结果
     */
    public TradeResult processInitOrder(ExOrder newOrder) {
        if (newOrder == null) {
            log.warn("订单为空，无法处理");
            return new TradeResult();
        }
        if (newOrder.getStatus() == null || !newOrder.getStatus().equals(OrderStatus.INIT.getCode())) {
            log.warn("只能处理状态为0的init订单，当前状态: {} - OrderId: {}",
                    newOrder.getStatus(), newOrder.getId());
            return new TradeResult();
        }
        String symbol = newOrder.getSymbol();
        if (symbol == null) {
            log.warn("订单交易对为空，无法处理 - OrderId: {}", newOrder.getId());
            return new TradeResult();
        }
        return newMatchingEngine.processInitOrder(newOrder, symbol);
    }

    /**
     * 检查订单是否可以进入撮合
     *
     * @param order 订单
     * @return 是否可以撮合
     */
    public boolean canProcess(ExOrder order) {
        if (order == null) {
            return false;
        }
        if (order.getStatus() == null || !order.getStatus().equals(OrderStatus.INIT.getCode())) {
            return false;
        }
        if (order.getSymbol() == null || order.getSide() == null || order.getVolume() == null) {
            log.warn("订单缺少必要字段 - OrderId: {}, Symbol: {}, Side: {}, Volume: {}",
                    order.getId(), order.getSymbol(), order.getSide(), order.getVolume());
            return false;
        }
        return true;
    }
}
