package com.market.consumer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.market.model.SpotAssetChangeMessage;
import com.market.service.SpotBroadcastService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

/**
 * 现货资产/订单变动 Kafka 消费者
 * <p>
 * 监听撮合模块发布的资产/订单变动消息，触发 WebSocket 推送。
 *
 * @author system
 * @date 2026-05-07
 */
@Component
public class SpotAssetChangeConsumer {

    private static final Logger log = LoggerFactory.getLogger(SpotAssetChangeConsumer.class);

    private final SpotBroadcastService broadcastService;
    private final ObjectMapper         objectMapper;

    public SpotAssetChangeConsumer(SpotBroadcastService broadcastService) {
        this.broadcastService = broadcastService;
        this.objectMapper     = new ObjectMapper();
    }

    /**
     * 消费资产/订单变动消息
     *
     * @param record Kafka 消息记录
     * @param ack    手动提交偏移量
     */
    @KafkaListener(
            topics       = "${spot.kafka.topic.asset-change:SPOT_CHANGE}",
            groupId      = "${spot.kafka.consumer.group-id:spot-market-group}",
            concurrency  = "1"
    )
    public void onAssetChange(ConsumerRecord<String, String> record, Acknowledgment ack) {
        try {
            SpotAssetChangeMessage message = objectMapper.readValue(record.value(), SpotAssetChangeMessage.class);
            broadcastService.broadcast(message);
        } catch (Exception e) {
            log.error("处理现货资产变动消息失败: topic={}, offset={}, value={}",
                    record.topic(), record.offset(), record.value(), e);
        } finally {
            ack.acknowledge();
        }
    }
}
