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.BytesDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.Bytes;
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.*;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import org.springframework.kafka.requestreply.CorrelationKey;
import org.springframework.kafka.requestreply.ReplyingKafkaTemplate;
import org.springframework.kafka.support.serializer.JsonSerializer;

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("${ervu.kafka.bootstrap.servers}")
  private String bootstrapServers;
  @Value("${ervu.kafka.security.protocol}")
  private String securityProtocol;
  @Value("${ervu.kafka.doc.login.module}")
  private String loginModule;
  @Value("${ervu.kafka.username}")
  private String username;
  @Value("${ervu.kafka.password}")
  private String password;
  @Value("${ervu.kafka.sasl.mechanism}")
  private String saslMechanism;

  @Value("${ervu.kafka.reply.topic}")
  private String replyTopic;
  @Value("${ervu.kafka.recruit.reply.topic}")
  private String recruitReplyTopic;
  @Value("${ervu.kafka.registry.extract.reply.topic}")
  private String registryExtractReplyTopic;

  @Value("${ervu.kafka.group.id}")
  private String groupId;
  @Value("${ervu.kafka.reply.timeout:30}")
  private long replyTimeout;

  @Bean
  public ProducerFactory<String, String> producerFactory() {
    Map<String, Object> configProps = producerConfig();
    configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    return new DefaultKafkaProducerFactory<>(configProps);
  }

  @Bean
  public ProducerFactory<String, Object> subpoenaProducerFactory() {
    Map<String, Object> configProps = producerConfig();
    configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
    return new DefaultKafkaProducerFactory<>(configProps);
  }

  private Map<String, Object> producerConfig() {
    Map<String, Object> configProps = new HashMap<>();
    configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
    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);
    configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    return configProps;
  }

  @Bean
  public ConsumerFactory<String, String> consumerFactory() {
    Map<String, Object> configProps = consumerConfig();
    configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    return new DefaultKafkaConsumerFactory<>(configProps);
  }

  @Bean
  public ConsumerFactory<String, Bytes> subpoenaConsumerFactory() {
    Map<String, Object> configProps = consumerConfig();
    configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, BytesDeserializer.class);
    return new DefaultKafkaConsumerFactory<>(configProps);
  }

  private Map<String, Object> consumerConfig() {
    Map<String, Object> configProps = new HashMap<>();
    configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
    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);
    configProps.put(ConsumerConfig.GROUP_ID_CONFIG, groupId + "-" + UUID.randomUUID());
    configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    return configProps;
  }

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

  @Bean
  public ConcurrentKafkaListenerContainerFactory<String, Bytes> subpoenaKafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, Bytes> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(subpoenaConsumerFactory());
    return factory;
  }

  @Bean
  public ConcurrentMessageListenerContainer<String, String> replyContainer(
      ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory) {
    return kafkaListenerContainerFactory.createContainer(replyTopic);
  }

  @Bean
  public ConcurrentMessageListenerContainer<String, Bytes> subpoenaReplyContainer(
      ConcurrentKafkaListenerContainerFactory<String, Bytes> subpoenaKafkaListenerContainerFactory) {
    return subpoenaKafkaListenerContainerFactory.createContainer(recruitReplyTopic, registryExtractReplyTopic);
  }

  @Bean("person")
  public ReplyingKafkaTemplate<String, String, String> replyingKafkaTemplate(
      ProducerFactory<String, String> producerFactory,
      ConcurrentMessageListenerContainer<String, String> replyContainer) {
    ReplyingKafkaTemplate<String, String, String> replyingKafkaTemplate =
        new ReplyingKafkaTemplate<>(producerFactory, replyContainer);
    customizeTemplate(replyingKafkaTemplate);
    return replyingKafkaTemplate;
  }

  @Bean("recruit")
  public ReplyingKafkaTemplate<String, Object, Bytes> subpoenaReplyingKafkaTemplate(
      ProducerFactory<String, Object> subpoenaProducerFactory,
      ConcurrentMessageListenerContainer<String, Bytes> subpoenaReplyContainer) {
    ReplyingKafkaTemplate<String, Object, Bytes> replyingKafkaTemplate =
        new ReplyingKafkaTemplate<>(subpoenaProducerFactory, subpoenaReplyContainer);
    customizeTemplate(replyingKafkaTemplate);
    return replyingKafkaTemplate;
  }

  private void customizeTemplate(ReplyingKafkaTemplate<?, ?, ?> replyingKafkaTemplate) {
    replyingKafkaTemplate.setCorrelationHeaderName("messageId");
    replyingKafkaTemplate.setCorrelationIdStrategy(record ->
        new CorrelationKey(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8)));
    replyingKafkaTemplate.setDefaultReplyTimeout(Duration.ofSeconds(replyTimeout));
    replyingKafkaTemplate.setSharedReplyTopic(true);
  }
}
