
using Microsoft.Extensions.Logging;
using OnlineSalesAutoCrop.CoreAPI.Models.Responses.Integrations;
using OnlineSalesAutoCrop.CoreAPI.Models.Responses.MobileApp;
using OnlineSalesAutoCrop.CoreAPI.Services.Contracts.Integrations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;

namespace OnlineSalesAutoCrop.CoreAPI.Services.Services.Integrations;

public class IntegrationHttpService : IIntegrationHttpService
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<IntegrationHttpService> _logger;

    public IntegrationHttpService(HttpClient httpClient, ILogger<IntegrationHttpService> logger)
    {
        _httpClient = httpClient;
        _logger = logger;
    }

    public async Task<IntegrationCustLedgerHttpResponse> GetCustomerLedgerAsync(string customerNumber, string companyCode, CancellationToken cancellationToken = default)
    {
        try
        {
            var requestUri = $"http/get_customer_ledger?customer={Uri.EscapeDataString(customerNumber)}&company={Uri.EscapeDataString(companyCode)}";

            var response = await _httpClient.GetAsync(requestUri, cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                var body = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("Customer ledger call failed: {StatusCode} — {Body}", response.StatusCode, body);
                response.EnsureSuccessStatusCode();
            }
            var payload= await response.Content.ReadFromJsonAsync< SapODataResponse<IntegrationCustLedgerHttpResponse>>(cancellationToken: cancellationToken);

            return payload?.D.Results.FirstOrDefault();
        }
        catch(Exception)
        {
            throw;
        }
    }

    public async Task<IList<IntegrationMaterialStockHttpResponse>> GetMaterialStockAsync(string plantCode, CancellationToken cancellationToken = default)
    {
        try
        {
            var requestUri = $"http/get_plantwise_available_stocks?plant={Uri.EscapeDataString(plantCode)}";

            var response = await _httpClient.GetAsync(requestUri, cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                var body = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("Material Stock call failed: {StatusCode} — {Body}", response.StatusCode, body);
                response.EnsureSuccessStatusCode();
            }

            var payload = await response.Content.ReadFromJsonAsync<SapODataResponse<IntegrationMaterialStockHttpResponse>>(cancellationToken: cancellationToken);

            return payload?.D.Results;
        }
        catch (Exception)
        {
            throw;
        }
    }

    public async Task<string> SendSAPOrdersAsync(GetOrderForSAPResponse request, CancellationToken cancellationToken = default)
    {
        try
        {
            var requestUri = "http/sales_order";

            var response = await _httpClient.PostAsJsonAsync(requestUri,request,cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                var body = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("Save Orders call failed: {StatusCode} — {Body}", response.StatusCode, body);
                response.EnsureSuccessStatusCode();
                return body;
            }

            var payload = await response.Content.ReadFromJsonAsync<SapODataResponse<IntegrationMaterialStockHttpResponse>>(cancellationToken: cancellationToken);

            return string.Empty ;
        }
        catch (Exception)
        {
            throw;
        }
    }
}
