package com.spot.mq;

import com.alibaba.fastjson.JSON;
import com.spot.dto.mq.PriceMessage;
import com.spot.service.NewMatchingEngine;
import com.spot.utils.MessageIdFilter;
import com.spot.utils.PriceCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

/**
 * 现货价格更新 Kafka 消费者
 * 监听 SPOT_NEW_PRICE Topic，更新价格缓存并触发挂单撮合
 *
 * @author jean
 * @date 2026-05-07
 */
@Slf4j
@Component
public class SpotNewPriceConsumer {

    @Autowired
    private NewMatchingEngine newMatchingEngine;

    @Autowired
    private MessageIdFilter messageIdFilter;

    /**
     * 消费价格更新消息
     *
     * @param record         Kafka 消息
     * @param acknowledgment 手动确认对象
     */
    @KafkaListener(
            topics = "${kafka.topic.price:SPOT_NEW_PRICE}",
            groupId = "${kafka.consumer.group.price:spot-match-price-group}",
            containerFactory = "kafkaListenerContainerFactory"
    )
    public void consume(ConsumerRecord<String, String> record, Acknowledgment acknowledgment) {
        String value = record.value();
        try {
            if (value == null || value.trim().isEmpty()) {
                acknowledgment.acknowledge();
                return;
            }

            // 幂等检查
            String msgId = record.key();
            if (msgId != null && messageIdFilter.isProcessed(msgId)) {
                acknowledgment.acknowledge();
                return;
            }

            // 解析价格消息
            PriceMessage priceMessage = JSON.parseObject(value, PriceMessage.class);
            if (priceMessage == null || priceMessage.getSymbol() == null || priceMessage.getPrice() == null) {
                log.error("价格消息解析失败或字段缺失 - Value: {}", value);
                acknowledgment.acknowledge();
                return;
            }

            // 补充时间戳
            if (priceMessage.getTimestamp() == null) {
                priceMessage.setTimestamp(com.spot.utils.TimeUtils.currentUtcTimestamp());
            }

            // 更新价格缓存并触发挂单撮合
            PriceCache.updatePrice(priceMessage);
            newMatchingEngine.processOnPriceUpdate(priceMessage.getSymbol(), priceMessage.getPrice());

            if (msgId != null) {
                messageIdFilter.markAsProcessed(msgId);
            }
            acknowledgment.acknowledge();

        } catch (Exception e) {
            log.error("处理价格更新消息失败 - Value: {}", value, e);
            // 不 ack，触发重试
        }
    }
}
