package com.lingyue.parse.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ配置
 * 用于异步任务处理
 * 
 * @author lingyue
 * @since 2026-01-14
 */
@Slf4j
@Configuration
public class RabbitMQConfig {
    
    /**
     * 解析任务队列名称
     */
    public static final String PARSE_TASK_QUEUE = "parse.task.queue";
    
    /**
     * 解析任务重试队列名称
     */
    public static final String PARSE_TASK_RETRY_QUEUE = "parse.task.retry.queue";
    
    /**
     * 解析任务死信队列名称
     */
    public static final String PARSE_TASK_DLQ = "parse.task.dlq";
    
    /**
     * 创建解析任务队列
     */
    @Bean
    public Queue parseTaskQueue() {
        return new Queue(PARSE_TASK_QUEUE, true, false, false);
    }
    
    /**
     * 创建解析任务重试队列
     */
    @Bean
    public Queue parseTaskRetryQueue() {
        return new Queue(PARSE_TASK_RETRY_QUEUE, true, false, false);
    }
    
    /**
     * 创建解析任务死信队列
     */
    @Bean
    public Queue parseTaskDlq() {
        return new Queue(PARSE_TASK_DLQ, true, false, false);
    }
    
    /**
     * JSON消息转换器
     */
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
    
    /**
     * RabbitTemplate配置
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(jsonMessageConverter());
        return template;
    }
    
    /**
     * 监听器容器工厂配置
     */
    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(jsonMessageConverter());
        // 单线程处理，符合GPU线性处理约束
        factory.setConcurrentConsumers(1);
        factory.setMaxConcurrentConsumers(1);
        factory.setPrefetchCount(1);
        return factory;
    }
}
