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

import static com.iqser.red.service.persistence.management.v1.processor.configuration.MessagingConfiguration.MIGRATION_DLQ;
import static com.iqser.red.service.persistence.management.v1.processor.configuration.MessagingConfiguration.MIGRATION_REQUEST_QUEUE;
import static com.iqser.red.service.persistence.management.v1.processor.configuration.MessagingConfiguration.MIGRATION_RESPONSE_QUEUE;
import static com.iqser.red.service.persistence.management.v1.processor.configuration.MessagingConfiguration.X_ERROR_INFO_HEADER;

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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.iqser.red.service.persistence.management.v1.processor.migration.SaasMigrationService;
import com.iqser.red.service.redaction.v1.model.MigrationRequest;
import com.iqser.red.service.redaction.v1.model.MigrationResponse;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class RedactionServiceSaasMigrationMessageReceiver {

    private final SaasMigrationService saasMigrationService;
    private final ObjectMapper objectMapper;


    @SneakyThrows
    @RabbitListener(queues = MIGRATION_RESPONSE_QUEUE)
    public void receive(MigrationResponse response) {

        saasMigrationService.handleEntityLogMigrationFinished(response.getDossierId(), response.getFileId());

        log.info("Received message {} in {}", response, MIGRATION_RESPONSE_QUEUE);
    }


    @SneakyThrows
    @RabbitListener(queues = MIGRATION_DLQ)
    public void handleDLQMessage(Message failedMessage) {

        var migrationRequest = objectMapper.readValue(failedMessage.getBody(), MigrationRequest.class);
        String errorCause = failedMessage.getMessageProperties().getHeader(X_ERROR_INFO_HEADER);
        if (errorCause == null) {
            errorCause = "Error occured during entityLog migration!";
        }
        saasMigrationService.handleError(migrationRequest.getDossierId(), migrationRequest.getFileId(), errorCause, MIGRATION_REQUEST_QUEUE);

    }

}
