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

import java.io.IOException;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Service;

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 com.iqser.red.service.persistence.management.v1.processor.service.persistence.DownloadStatusPersistenceService;
import com.iqser.red.service.persistence.service.v1.api.shared.model.download.DownloadStatusValue;
import com.iqser.red.service.redaction.report.v1.api.model.ReportRequestMessage;
import com.iqser.red.service.redaction.report.v1.api.model.ReportResultMessage;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class DownloadDLQMessageReceiver {

    private final DownloadStatusPersistenceService downloadStatusPersistenceService;
    private final ObjectMapper objectMapper;
    private final RetryTemplate retryTemplate;


    @RabbitListener(queues = MessagingConfiguration.DOWNLOAD_DLQ)
    public void handleDlqMessage(DownloadJob downloadJob) throws IOException {

        log.warn("Handling download job in DLQ userId: {} storageId: {} - setting status to error!", downloadJob.getUserId(), downloadJob.getStorageId());
        setDownloadFailed(downloadJob.getUserId(), downloadJob.getStorageId());
    }


    public void setDownloadFailed(String userId, String downloadId) {

        retryTemplate.execute(retryContext -> {
            log.warn("Retrying {} time to set FAILED status for downloadJob userId: {} storageId: {}", retryContext.getRetryCount(), userId, downloadId);
            downloadStatusPersistenceService.updateStatus(downloadId, DownloadStatusValue.FAILED);
            return null;
        });
    }


    @RabbitListener(queues = MessagingConfiguration.REPORT_DLQ)
    public void handleReportDlqMessage(ReportRequestMessage reportRequestMessage) {

        log.warn("Handling report request in DLQ userId: {} storageId: {} - setting status to error!", reportRequestMessage.getUserId(), reportRequestMessage.getDownloadId());
        setDownloadFailed(reportRequestMessage.getUserId(), reportRequestMessage.getDownloadId());
    }


    @RabbitListener(queues = MessagingConfiguration.REPORT_RESULT_DLQ)
    public void handleReportResponseDlqMessage(ReportResultMessage reportResultMessage) {

        log.warn("Handling report request in DLQ userId: {} storageId: {} - setting status to error!", reportResultMessage.getUserId(), reportResultMessage.getDownloadId());
        setDownloadFailed(reportResultMessage.getUserId(), reportResultMessage.getDownloadId());
    }

}
