package com.smyhub.store.mengyastorebackendjava.config;

import com.smyhub.store.mengyastorebackendjava.mq.RabbitMQTopology;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.*;
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.core.AcknowledgeMode;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(name = "app.rabbitmq-enabled", havingValue = "true")
public class RabbitMQConfig {

    private final AppProperties appProperties;

    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @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());
        factory.setPrefetchCount(1);
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }

    @Bean
    public TopicExchange orderEmailExchange() {
        String name = RabbitMQTopology.exchangeName(appProperties.getRabbitmqEnv());
        return ExchangeBuilder.topicExchange(name).durable(true).build();
    }

    @Bean
    public Queue orderEmailQueue() {
        String name = RabbitMQTopology.queueName(appProperties.getRabbitmqEnv());
        return QueueBuilder.durable(name).build();
    }

    @Bean
    public Binding orderEmailBinding() {
        return BindingBuilder
                .bind(orderEmailQueue())
                .to(orderEmailExchange())
                .with(RabbitMQTopology.ORDER_EMAIL_ROUTING_KEY);
    }
}
