// EN: HTTP client implementation for calling inventory-service API.
// VI: Trien khai HTTP client de goi API cua inventory-service.

using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.Logging;

namespace FnbEngine.Infrastructure.ExternalServices;

/// <summary>
/// EN: HTTP client for inventory-service with Polly retry policies.
/// VI: HTTP client cho inventory-service voi Polly retry policies.
/// </summary>
public class InventoryServiceClient : IInventoryServiceClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<InventoryServiceClient> _logger;

    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        PropertyNameCaseInsensitive = true
    };

    public InventoryServiceClient(
        HttpClient httpClient,
        ILogger<InventoryServiceClient> logger)
    {
        _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <summary>
    /// EN: Deduct inventory by calling POST /api/v1/inventory/deduct on inventory-service.
    /// VI: Tru kho bang cach goi POST /api/v1/inventory/deduct tren inventory-service.
    /// </summary>
    public async Task<bool> DeductInventoryAsync(DeductInventoryRequest request, CancellationToken cancellationToken = default)
    {
        _logger.LogInformation(
            "EN: Sending inventory deduction request / VI: Gui yeu cau tru kho - ReferenceId: {ReferenceId}, Items: {ItemCount}",
            request.ReferenceId, request.Items.Count);

        try
        {
            var response = await _httpClient.PostAsJsonAsync(
                "api/v1/inventory/deduct",
                request,
                JsonOptions,
                cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation(
                    "EN: Inventory deduction API call succeeded / VI: Goi API tru kho thanh cong - ReferenceId: {ReferenceId}",
                    request.ReferenceId);
                return true;
            }

            var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
            _logger.LogWarning(
                "EN: Inventory deduction API call failed / VI: Goi API tru kho that bai - StatusCode: {StatusCode}, Error: {Error}",
                response.StatusCode, errorContent);

            return false;
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex,
                "EN: HTTP error calling inventory service / VI: Loi HTTP khi goi inventory service - ReferenceId: {ReferenceId}",
                request.ReferenceId);
            return false;
        }
        catch (TaskCanceledException ex)
        {
            _logger.LogWarning(ex,
                "EN: Inventory service call timed out / VI: Goi inventory service bi timeout - ReferenceId: {ReferenceId}",
                request.ReferenceId);
            return false;
        }
    }
}
