package ru.micord.ervu.kafka.service.impl;

import java.nio.charset.StandardCharsets;

import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.header.internals.RecordHeader;
import org.apache.kafka.common.utils.Bytes;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.requestreply.ReplyingKafkaTemplate;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.stereotype.Service;
import ru.micord.ervu.dto.SubpoenaRequestDto;

/**
 * @author gulnaz
 */
@Service
@Qualifier("recruit")
public class SubpoenaReplyingKafkaService extends BaseReplyingKafkaService<Object, Bytes> {

  private final ReplyingKafkaTemplate<String, Object, Bytes> replyingKafkaTemplate;

  @Value("${ervu.kafka.recruit.header.class}")
  private String recruitHeaderClass;
  @Value("${ervu.kafka.extract.header.class}")
  private String extractHeaderClass;

  public SubpoenaReplyingKafkaService(@Qualifier("recruit")
      ReplyingKafkaTemplate<String, Object, Bytes> replyingKafkaTemplate) {
    this.replyingKafkaTemplate = replyingKafkaTemplate;
  }

  @Override
  protected ReplyingKafkaTemplate<String, Object, Bytes> getTemplate() {
    return replyingKafkaTemplate;
  }

  @Override
  protected ProducerRecord<String, Object> getProducerRecord(String requestTopic, String replyTopic,
                                                             Object requestMessage) {
    ProducerRecord<String, Object> record = new ProducerRecord<>(requestTopic, requestMessage);
    record.headers().add(new RecordHeader(KafkaHeaders.REPLY_TOPIC, replyTopic.getBytes()));
    String headerClass = requestMessage instanceof SubpoenaRequestDto
                         ? recruitHeaderClass : extractHeaderClass;
    record.headers().add("class", headerClass.getBytes(StandardCharsets.UTF_8));
    return record;
  }
}
