
using Microsoft.Extensions.Logging;
using OnlineSalesAutoCrop.CoreAPI.Models;
using OnlineSalesAutoCrop.CoreAPI.Models.Requests.MobileApp;
using OnlineSalesAutoCrop.CoreAPI.Services.Contracts.BackgroupJobs;
using OnlineSalesAutoCrop.CoreAPI.Services.Contracts.Integrations;
using OnlineSalesAutoCrop.CoreAPI.Services.Contracts.MobileApp;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace OnlineSalesAutoCrop.CoreAPI.Services.Services.BackgroupJobs;

public class BackgroundJobService : IBackgroundJobService
{
    private readonly IIntegrationHttpService _httpService;
    private readonly IOrderService _orderService;
    private readonly ILogger<BackgroundJobService> _logger;

    public BackgroundJobService(IIntegrationHttpService httpService, IOrderService orderService, ILogger<BackgroundJobService> logger)
    {
        _httpService = httpService;
        _orderService = orderService;
        _logger = logger;
    }

    public async Task ExecuteSendingOrderAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("SendingOrder Job successfully run at: " + DateTime.Now.ToString());
        try
        {
            var pendingOrderIds = await _orderService.GetAvailableOrderIdsForSAPAsync(SAPOrderStatusEnum.Pending);
            foreach (var item in pendingOrderIds)
            {
                var orderDetails = await _orderService.GetOrderDetailsForSapByIdAsync(item);

                string httpResponse = await _httpService.SendSAPOrdersAsync(orderDetails);
                await _orderService.UpdateSendingSapDetailsAsync(new UpdateSapDetailsRequest
                {
                    OrderId = item,
                    SentAt = DateTime.Now,
                    RetryCount =1,
                    ReturnMessage = httpResponse
                });
            }
        }
        catch(Exception ex)
        {
            _logger.LogError("Exception Occur  in  ExecuteSendingOrder "+ ex.Message);
            throw;
        }

        _logger.LogInformation("SendingOrder Job successfully finished at: " + DateTime.Now.ToString());
    }
}
