using CashLineERP.Application.Integration;
using CashLineERP.Application.Internal;
using CashLineERP.Contracts.Integration;
using CashLineERP.Contracts.Tax;

namespace CashLineERP.Application.Tax;

public sealed class EtaNotificationOperationsService : IEtaNotificationOperationsService
{
    private readonly IInboxMessageService _inboxMessageService;
    private readonly IEtaAuthorityCallbackService _etaAuthorityCallbackService;
    private readonly IInternalWorkbenchService _internalWorkbenchService;

    public EtaNotificationOperationsService(
        IInboxMessageService inboxMessageService,
        IEtaAuthorityCallbackService etaAuthorityCallbackService,
        IInternalWorkbenchService internalWorkbenchService)
    {
        _inboxMessageService = inboxMessageService;
        _etaAuthorityCallbackService = etaAuthorityCallbackService;
        _internalWorkbenchService = internalWorkbenchService;
    }

    public IReadOnlyCollection<InboxMessageResponse> GetNotifications(string? statusCode = null) =>
        _inboxMessageService.GetInboxMessages(statusCode, "ETA");

    public InboxMessageResponse? GetNotification(long inboxMessageId)
    {
        var message = _inboxMessageService.GetInboxMessage(inboxMessageId);
        return message is not null && string.Equals(message.IntegrationProviderCode, "ETA", StringComparison.OrdinalIgnoreCase)
            ? message
            : null;
    }

    public ProcessEtaDocumentNotificationBatchResultResponse ProcessPendingNotifications(ProcessEtaDocumentNotificationBatchRequest request) =>
        _etaAuthorityCallbackService.ProcessPendingNotifications(request);

    public EtaNotificationProcessingReceiptResponse ReprocessNotification(long inboxMessageId, long actorUserId, ReprocessEtaDocumentNotificationRequest request) =>
        _etaAuthorityCallbackService.ProcessNotification(inboxMessageId, request.ProcessorCode, request.RetryDelaySeconds);

    public EtaNotificationMonitoringResponse GetMonitoring(int itemLimit = 10)
    {
        var normalizedLimit = Math.Clamp(itemLimit, 1, 25);
        var received = _inboxMessageService.GetInboxMessages("RECEIVED", "ETA");
        var retry = _inboxMessageService.GetInboxMessages("RETRY", "ETA");
        var failed = _inboxMessageService.GetInboxMessages("FAILED", "ETA");
        var deadLetter = _inboxMessageService.GetInboxMessages("DEAD_LETTER", "ETA");
        var dashboard = _internalWorkbenchService.GetDashboardSummary();

        var recentNotifications = received
            .Concat(retry)
            .Concat(failed)
            .Concat(deadLetter)
            .OrderByDescending(item => item.CreatedAtUtc)
            .Take(normalizedLimit)
            .ToArray();

        return new EtaNotificationMonitoringResponse(
            DateTime.UtcNow,
            received.Count,
            retry.Count,
            failed.Count,
            deadLetter.Count,
            dashboard.EtaAttentionCount,
            recentNotifications);
    }
}
