package dp.kotul.starter.messaging.config

import com.fasterxml.jackson.databind.ObjectMapper
import dp.kotul.starter.messaging.model.TEMPLATE_GROUPS_EXCHANGE
import org.springframework.amqp.core.TopicExchange
import org.springframework.amqp.rabbit.connection.ConnectionFactory
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.scheduling.annotation.EnableScheduling

@EnableScheduling
@Configuration
class RabbitConfiguration {

    @Bean
    @Qualifier(TEMPLATE_GROUPS_EXCHANGE)
    fun templateGroupsExchange(): TopicExchange {
        return TopicExchange(TEMPLATE_GROUPS_EXCHANGE, true, false)
    }

    @Bean
    @ConditionalOnMissingBean
    fun messageConverter(mapper: ObjectMapper): Jackson2JsonMessageConverter {
        return Jackson2JsonMessageConverter(mapper)
    }

    @Bean
    @ConditionalOnMissingBean
    fun rabbitTemplate(connectionFactory: ConnectionFactory, messageConverter: Jackson2JsonMessageConverter): RabbitTemplate {
        val rabbitTemplate = RabbitTemplate(connectionFactory)
        rabbitTemplate.messageConverter = messageConverter
        return rabbitTemplate
    }
}
