package com.fs.newAdv.event;


import com.fs.common.utils.TraceIdUtil;
import com.fs.newAdv.constant.ConversionTrackingMessage;
import com.fs.newAdv.constant.MqTopicConstant;
import com.fs.newAdv.enums.SystemEventTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 转化事件监听器
 * 监听转化事件并发送到MQ进行异步处理
 *
 * @author zhangqin
 * @date 2025-11-03
 * @updated 2025-11-05 重构为发送MQ消息
 */
@Slf4j
@Component
public class ConversionEventListener {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 处理转化事件
     * 将转化事件转换为MQ消息并发送
     *
     * @param event 转化事件
     */
    @Async
    @EventListener
    public void handleConversionEvent(ConversionEvent event) {
        String traceId = event.getTraceId();
        SystemEventTypeEnum eventType = event.getEventType();
        Double value = event.getValue();
        log.info("接收到转化事件 | traceId={}, eventType={} ,value={}",
                traceId, eventType, value);
        String trackId = TraceIdUtil.get();
        // 1. 校验参数
        // 2. 构建MQ消息
        ConversionTrackingMessage message = new ConversionTrackingMessage();
        message.setTraceId(traceId);
        message.setEventType(eventType);
        message.setValue(value);
        message.setTrackId(trackId);
        // 3. 异步发送消息
        rocketMQTemplate.asyncSend(
                MqTopicConstant.CONVERSION_TRACKING_TOPIC,
                message,
                new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        log.error("转化消息发送成功:{}", trackId);
                    }

                    @Override
                    public void onException(Throwable e) {
                        log.error("转化消息发送失败:{}", trackId,e);
                        // TODO: 记录到数据库，后续补偿
                    }
                }
        );
    }
}
