package com.iqser.red.service.persistence.management.v1.processor.service.download;

import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.iqser.red.service.persistence.management.v1.processor.configuration.MessagingConfiguration;
import com.iqser.red.service.redaction.report.v1.api.model.ReportResultMessage;

import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
public class DownloadReportMessageReceiver {

    ObjectMapper objectMapper;
    DownloadPreparationService downloadPreparationService;


    @SneakyThrows
    @RabbitHandler
    @RabbitListener(queues = MessagingConfiguration.REPORT_RESULT_QUEUE)
    public void receive(Message message) {

        ReportResultMessage reportResultMessage = objectMapper.readValue(message.getBody(), ReportResultMessage.class);

        // This prevents from endless retries oom errors.
        if (message.getMessageProperties().isRedelivered()) {
            throw new AmqpRejectAndDontRequeueException(String.format("Error during last processing of request with downloadId: %s, do not retry.",
                    reportResultMessage.getDownloadId()));
        }

        receive(reportResultMessage);
    }


    public void receive(ReportResultMessage reportResultMessage) throws JsonProcessingException {

        log.info("Received request for userId:{} downloadId:{}", reportResultMessage.getUserId(), reportResultMessage.getDownloadId());
        downloadPreparationService.createDownload(reportResultMessage);
    }

}
