package ru.ibs.socrates.confexporter.external.sdtllmraggateconf.rabbitmq.config;

import org.springframework.amqp.rabbit.annotation.RabbitListenerConfigurer;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistrar;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.ContentTypeResolver;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;


/**
 * jackson2Converter для rabbitmq.
 */
@Configuration
public class SdtLlmRagGateConfRabbitListenerConfigurer implements RabbitListenerConfigurer {

  /**
   * jackson2Converter.
   * @return
   */
  @Bean
  public MessageConverter jackson2Converter() {
    MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
    converter.setContentTypeResolver(masstransitContentTypeResolver());
    return converter;
  }

  /**
   * myHandlerMethodFactory.
   * @return
   */
  @Bean
  public DefaultMessageHandlerMethodFactory myHandlerMethodFactory() {
    DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
    factory.setMessageConverter(jackson2Converter());
    return factory;
  }

  /**
   * configureRabbitListeners.
   */
  @Override
  public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
    registrar.setMessageHandlerMethodFactory(myHandlerMethodFactory());
  }

  private ContentTypeResolver masstransitContentTypeResolver() {
    return headers -> {
      if (headers == null || headers.get(MessageHeaders.CONTENT_TYPE) == null) {
        return null;
      }

      Object contentTypeHeader = headers.get(MessageHeaders.CONTENT_TYPE);
      String contentType;
      if (contentTypeHeader instanceof MimeType) {
        contentType = ((MimeType) contentTypeHeader).toString();
      } else if (contentTypeHeader instanceof String) {
        contentType = (String) contentTypeHeader;
      } else {
        return null;
      }

      contentType = contentType.toLowerCase().trim();

      if (contentType.startsWith("application/vnd.masstransit+json")) {
        return MimeTypeUtils.APPLICATION_JSON;
      }

      return MimeTypeUtils.parseMimeType(contentType);
    };
  }
}
