using e_suite.Database.Audit;
using e_suite.Messaging.Common.models;
using e_suite.Service.WorkflowProcessor;
using eSuite.Core.Clock;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client.Events;

namespace e_suite.MessageProcessor.Handlers;

public class ActivityQueueHandler : QueueHandlerBase
{
    private readonly ILogger _logger;
    private readonly IClock _clock;
    private readonly IWorkflowProcessor _workflowProgressor;

    public ActivityQueueHandler(ILogger logger, IClock clock, IWorkflowProcessor workflowProgressor)
    {
        _logger = logger;
        _clock = clock;
        _workflowProgressor = workflowProgressor;
    }

    private readonly AuditUserDetails _auditUserDetails = new()
    {
        Comment = "ActivityQueueHandler",
        UserDisplayName = "Workflow processor"
    };

    public override async Task OnReceived(string queueName, BasicDeliverEventArgs basicDeliverEventArgs)
    {
        var activityMessage = await TranslateMessage<ActivityMessage>(basicDeliverEventArgs);
        _logger.LogInformation("{DateTime}: {MessageType} message received.", _clock.GetNow, activityMessage.MessageType);
        switch (activityMessage.MessageType)
        {
            case ActivityMessageTypes.ProgressActivity:
                var progressActivityMessage = await TranslateMessage<ProgressActivityMessage>(basicDeliverEventArgs);
                await _workflowProgressor.ProgressActivity(_auditUserDetails, progressActivityMessage.ActivityId, CancellationToken.None);
                break;
            default:
#pragma warning disable CA2208 // Instantiate argument exceptions correctly
                throw new ArgumentOutOfRangeException(nameof(activityMessage.MessageType), activityMessage.MessageType, "Unexpected message type");
#pragma warning restore CA2208 // Instantiate argument exceptions correctly
        }
        _logger.LogInformation("{DateTime}: {MessageType} message processing finished.", _clock.GetNow, activityMessage.MessageType);
    }
}