package ru.micord.ervu.kafka;

import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.config.SaslConfigs;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import org.springframework.kafka.requestreply.CorrelationKey;
import org.springframework.kafka.requestreply.ReplyingKafkaTemplate;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Configuration
@EnableKafka
public class ReplyingKafkaConfig {

  @Value("${kafka.hosts}")
  private String bootstrapServers;
  @Value("${ervu.kafka.org.reply.topic}")
  private String orgReplyTopic;
  @Value("${ervu.kafka.journal.reply.topic}")
  private String journalReplyTopic;
  @Value("${ervu.kafka.group.id}")
  private String groupId;
  @Value("${ervu.kafka.reply.timeout:30}")
  private long replyTimeout;
  @Value("${ervu.kafka.excerpt.reply.topic}")
  private String excerptReplyTopic;
  @Value("${kafka.auth_sec_proto}")
  private String securityProtocol;
  @Value("${kafka.auth_sasl_module}")
  private String loginModule;
  @Value("${kafka.user}")
  private String username;
  @Value("${kafka.pass}")
  private String password;
  @Value("${kafka.auth_sasl_mech}")
  private String saslMechanism;

  @Bean("ervuProducerFactory")
  public ProducerFactory<String, String> producerFactory() {
    Map<String, Object> configProps = new HashMap<>();
    configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
    configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    configProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, securityProtocol);
    configProps.put(SaslConfigs.SASL_JAAS_CONFIG, loginModule + " required username=\""
                                            + username + "\" password=\"" + password + "\";");
    configProps.put(SaslConfigs.SASL_MECHANISM, saslMechanism);
    return new DefaultKafkaProducerFactory<>(configProps);
  }

  @Bean
  public ConsumerFactory<String, String> consumerFactory() {
    Map<String, Object> configProps = new HashMap<>();
    configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
    configProps.put(ConsumerConfig.GROUP_ID_CONFIG, groupId + "-" + UUID.randomUUID());
    configProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
    configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    configProps.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, securityProtocol);
    configProps.put(SaslConfigs.SASL_JAAS_CONFIG, loginModule + " required username=\""
                                                  + username + "\" password=\"" + password + "\";");
    configProps.put(SaslConfigs.SASL_MECHANISM, saslMechanism);
    return new DefaultKafkaConsumerFactory<>(configProps);
  }

  @Bean("ervuContainerFactory")
  public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory =
        new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(consumerFactory());
    return factory;
  }

  @Bean
  public ConcurrentMessageListenerContainer<String, String> replyContainer(
      @Qualifier("ervuContainerFactory") ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory) {
    return kafkaListenerContainerFactory.createContainer(orgReplyTopic, excerptReplyTopic, journalReplyTopic);
  }

  @Bean
  public ReplyingKafkaTemplate<String, String, String> replyingKafkaTemplate(
      @Qualifier("ervuProducerFactory") ProducerFactory<String, String> producerFactory,
      ConcurrentMessageListenerContainer<String, String> replyContainer) {
    ReplyingKafkaTemplate<String, String, String> replyingKafkaTemplate =
        new ReplyingKafkaTemplate<>(producerFactory, replyContainer);
    replyingKafkaTemplate.setCorrelationHeaderName("messageId");
    replyingKafkaTemplate.setCorrelationIdStrategy(record ->
        new CorrelationKey(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8)));
    replyingKafkaTemplate.setDefaultReplyTimeout(Duration.ofSeconds(replyTimeout));
    replyingKafkaTemplate.setSharedReplyTopic(true);
    return replyingKafkaTemplate;
  }
}
