using e_suite.API.Common;
using e_suite.Messaging.Common.models;
using e_suite.Service.Sentinel;
using eSuite.Core.Clock;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client.Events;

namespace e_suite.MessageProcessor.Handlers;

public class DatabaseQueueHandler : QueueHandlerBase
{
    private readonly ISentinelMaintenance _sentinelMaintenance;
    private readonly IPerformanceMaintenance _performanceMaintenance;
    private readonly IUserManagerMaintenance _userManagerMaintenance;
    private readonly ILogger _logger;
    private readonly IClock _clock;

    public DatabaseQueueHandler(ISentinelMaintenance sentinelMaintenance, IPerformanceMaintenance performanceMaintenance, IUserManagerMaintenance userManagerMaintenance, IClock clock, ILogger logger)
    {
        _clock = clock;
        _sentinelMaintenance = sentinelMaintenance;
        _performanceMaintenance = performanceMaintenance;
        _userManagerMaintenance = userManagerMaintenance;
        _logger = logger;
    }
    
    public override async Task OnReceived(string queueName, BasicDeliverEventArgs basicDeliverEventArgs)
    {
        var maintenanceMessage = await TranslateMessage<DatabaseMessage>(basicDeliverEventArgs);
        _logger.LogInformation("{DateTime}: {MessageType} message received.", _clock.GetNow, maintenanceMessage.MessageType);
        switch (maintenanceMessage.MessageType)
        {
            case DatabaseMessageTypes.ClearOldSentinelData:
                await _sentinelMaintenance.ClearOldSentinelData();
                break;
            case DatabaseMessageTypes.ClearOldPerformanceData:
                await _performanceMaintenance.ClearOldPerformanceData();
                break;
            case DatabaseMessageTypes.ClearOldEmailActions:
                await _userManagerMaintenance.ClearOldEmailActions();
                break;
            case DatabaseMessageTypes.ClearOldSingleUserGuids:
                await _userManagerMaintenance.ClearOldSingleUserGuids();
                break;
            default:
#pragma warning disable CA2208 // Instantiate argument exceptions correctly
                throw new ArgumentOutOfRangeException( nameof(maintenanceMessage.MessageType), maintenanceMessage.MessageType, "Unexpected message type");
#pragma warning restore CA2208 // Instantiate argument exceptions correctly
        }
        _logger.LogInformation("{DateTime}: {MessageType} message processing finished.", _clock.GetNow, maintenanceMessage.MessageType);
    }
}