package space.nstart.pcp.routepassportconsumer.config

import org.apache.kafka.clients.producer.ProducerConfig
import org.apache.kafka.common.serialization.StringSerializer
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.kafka.core.DefaultKafkaProducerFactory
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.kafka.core.ProducerFactory

/**
 * Явная producer-конфигурация для route-processing-service.
 *
 * В этом модуле Kafka producer bean'ы не поднимались автоконфигурацией,
 * поэтому template регистрируется явно.
 */
@Configuration
@ConditionalOnProperty(name = ["spring.kafka.bootstrap-servers"], matchIfMissing = false)
class KafkaProducerConfig(
    @param:Value("\${spring.kafka.bootstrap-servers}")
    private val bootstrapServers: String,

    @param:Value("\${spring.kafka.producer.acks:all}")
    private val acks: String,

    @param:Value("\${spring.kafka.producer.retries:10}")
    private val retries: Int,

    @param:Value("\${spring.kafka.producer.properties.enable.idempotence:true}")
    private val enableIdempotence: Boolean,

    @param:Value("\${spring.kafka.producer.properties.max.in.flight.requests.per.connection:5}")
    private val maxInFlightRequestsPerConnection: Int,
) {

    @Bean
    fun producerFactory(): ProducerFactory<String, String> =
        DefaultKafkaProducerFactory(
            mutableMapOf<String, Any>(
                ProducerConfig.BOOTSTRAP_SERVERS_CONFIG to bootstrapServers,
                ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG to StringSerializer::class.java,
                ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG to StringSerializer::class.java,
                ProducerConfig.ACKS_CONFIG to acks,
                ProducerConfig.RETRIES_CONFIG to retries,
                ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG to enableIdempotence,
                ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION to maxInFlightRequestsPerConnection,
            ),
        )

    @Bean
    fun kafkaTemplate(): KafkaTemplate<String, String> = KafkaTemplate(producerFactory())
}
