package org.dromara.common.mq.config;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.spring.autoconfigure.RocketMQAutoConfiguration;
import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQMessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * RocketMQ配置类
 * 确保RocketMQTemplate被正确初始化
 *
 * @author wzj
 */
@Configuration
@EnableConfigurationProperties(RocketMQProperties.class)
@ConditionalOnClass(DefaultMQProducer.class)
@Import(RocketMQAutoConfiguration.class)
public class RocketMQConfiguration {

    /**
     * 确保RocketMQTemplate被正确初始化
     * 这个Bean会由RocketMQAutoConfiguration自动创建
     * 此处仅作为备用方案
     */
    @Bean
    @ConditionalOnMissingBean(RocketMQTemplate.class)
    @ConditionalOnBean(DefaultMQProducer.class)
    public RocketMQTemplate rocketMQTemplate(DefaultMQProducer mqProducer,
                                            RocketMQMessageConverter messageConverter) {
        RocketMQTemplate rocketMQTemplate = new RocketMQTemplate();
        rocketMQTemplate.setProducer(mqProducer);
        rocketMQTemplate.setMessageConverter(messageConverter.getMessageConverter());
        return rocketMQTemplate;
    }

    @Bean
    @ConditionalOnMissingBean(RocketMQMessageConverter.class)
    public RocketMQMessageConverter rocketMQMessageConverter() {
        return new RocketMQMessageConverter();
    }
}
