package com.ktg.common.utils.rocketmq;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.MessageExt;
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 java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * RocketMQ自动配置类
 * 在Spring Boot应用启动时自动配置RocketMQ相关Bean
 */
@Configuration // 声明为配置类
@ConditionalOnClass(DefaultMQProducer.class) // 当类路径下有DefaultMQProducer类时生效
@EnableConfigurationProperties(RocketMQProperties.class) // 启用配置属性
public class RocketMQAutoConfiguration {

    /**
     * 创建生产者管理器Bean
     * @param properties RocketMQ配置属性
     * @return 生产者管理器实例
     */
    @Bean
    @ConditionalOnMissingBean // 当容器中没有该Bean时创建
    public RocketMQProducerManager rocketMQProducerManager(RocketMQProperties properties) {
        return new RocketMQProducerManager(properties);
    }

    /**
     * 创建默认的消息处理器Map
     * 应用可以通过@Bean提供自定义的消息处理器
     * @return 空的处理器Map
     */
    @Bean
    @ConditionalOnMissingBean
    public Map<String, Consumer<MessageExt>> rocketMQMessageHandlers() {
        return new HashMap<>();
    }

    /**
     * 创建消费者管理器Bean
     * @param properties RocketMQ配置属性
     * @param messageHandlers 消息处理器Map
     * @return 消费者管理器实例
     */
    @Bean
    @ConditionalOnMissingBean
    public RocketMQConsumerManager rocketMQConsumerManager(RocketMQProperties properties,
                                                           Map<String, Consumer<MessageExt>> messageHandlers) {
        return new RocketMQConsumerManager(properties, messageHandlers);
    }
}
