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.persistence.management.v1.processor.model.DownloadJob;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class DownloadMessageReceiver {

    private final DownloadProcessorService downloadProcessorService;
    private final ObjectMapper objectMapper;


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

        DownloadJob downloadJob = objectMapper.readValue(message.getBody(), DownloadJob.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.", downloadJob.getStorageId()));
        }

        receive(downloadJob);
    }


    public void receive(DownloadJob downloadJob) throws JsonProcessingException {

        log.info("Preparing download for userId: {} and storageId: {}", downloadJob.getUserId(), downloadJob.getStorageId());
        downloadProcessorService.processDownload(downloadJob);
    }

}
