package com.seer.teach.mall.app.order.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MQProducer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import jakarta.annotation.PreDestroy;

@ConditionalOnProperty(prefix = "mall.order", name = "delay.enabled", havingValue = "true", matchIfMissing = true)
@Service
@Slf4j
public class RocketMQConfig {

    @Value("${rocketmq.name-server:}")
    private String nameServer;

    @Value("${rocketmq.producer.group:}")
    private String producerGroup;

    @Value("${rocketmq.consumer.group:}")
    private String consumerGroup;

    @Value("${rocketmq.consumer.topic:}")
    private String consumerTopic;

    private DefaultMQProducer producer;

    @Bean
    public MQProducer rocketMQProducer() throws MQClientException {
        producer = new DefaultMQProducer(producerGroup);
        producer.setNamesrvAddr(nameServer);
        // 可以设置其他参数，如 sendMsgTimeout, retryTimesWhenSendFailed 等
        // producer.setSendMsgTimeout(3000);

        try {
            producer.start();
            log.info("RocketMQ Producer Started. Group: {}, NameServer: {}", producerGroup, nameServer);
        } catch (MQClientException e) {
            log.error("Failed to start RocketMQ Producer", e);
            throw e; // 启动失败，抛出异常阻止应用启动
        }
        return producer;
    }

     @PreDestroy
     public void destroy() {
         if (producer != null) {
             producer.shutdown();
         }
         log.info("RocketMQ Producer shutdown.");
     }
}
