// EN: HTTP client for Catalog Service.
// VI: HTTP client cho Catalog Service.

namespace OrderService.API.Infrastructure.HttpClients;

/// <summary>
/// EN: Client for calling Catalog Service to get product details.
/// VI: Client gọi Catalog Service để lấy chi tiết sản phẩm.
/// </summary>
public class CatalogServiceClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<CatalogServiceClient> _logger;

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

    /// <summary>
    /// EN: Get product by ID.
    /// VI: Lấy sản phẩm theo ID.
    /// </summary>
    public async Task<ProductDto?> GetProductByIdAsync(Guid productId, CancellationToken cancellationToken = default)
    {
        try
        {
            _logger.LogInformation(
                "EN: Getting product from Catalog Service / VI: Lấy sản phẩm từ Catalog Service: {ProductId}",
                productId);

            var response = await _httpClient.GetAsync(
                $"/api/v1/products/{productId}",
                cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                _logger.LogWarning(
                    "EN: Product not found in Catalog Service / VI: Không tìm thấy sản phẩm trong Catalog Service: {ProductId}",
                    productId);
                return null;
            }

            return await response.Content.ReadFromJsonAsync<ProductDto>(cancellationToken);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex,
                "EN: Error calling Catalog Service / VI: Lỗi khi gọi Catalog Service: {ProductId}",
                productId);
            throw;
        }
    }
}

/// <summary>
/// EN: Product DTO from Catalog Service.
/// VI: DTO sản phẩm từ Catalog Service.
/// </summary>
public record ProductDto(
    Guid Id,
    string Name,
    string Type,
    decimal Price,
    bool IsActive
);
