using Hangfire;
using Meezi.Core.Delivery;
using Meezi.API.Services.Delivery;

namespace Meezi.API.Jobs;

public class ProcessDeliveryOrderJob
{
    private readonly IDeliveryOrderProcessor _processor;
    private readonly ILogger<ProcessDeliveryOrderJob> _logger;

    public ProcessDeliveryOrderJob(
        IDeliveryOrderProcessor processor,
        ILogger<ProcessDeliveryOrderJob> logger)
    {
        _processor = processor;
        _logger = logger;
    }

    [AutomaticRetry(Attempts = 3, DelaysInSeconds = [10, 60, 300])]
    public async Task ExecuteAsync(
        string webhookLogId,
        UnifiedDeliveryOrder unified,
        CancellationToken cancellationToken)
    {
        var result = await _processor.ProcessAsync(webhookLogId, unified, cancellationToken);
        if (!result.Success && result.ErrorCode is not null)
            _logger.LogWarning(
                "Delivery process failed {Code}: {Message} (log {LogId})",
                result.ErrorCode,
                result.Message,
                webhookLogId);
    }
}
