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

namespace OrderService.API.Infrastructure.HttpClients;

/// <summary>
/// EN: Client for calling Inventory Service for stock operations.
/// VI: Client gọi Inventory Service để thực hiện thao tác kho.
/// </summary>
public class InventoryServiceClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<InventoryServiceClient> _logger;

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

    /// <summary>
    /// EN: Check if stock is available.
    /// VI: Kiểm tra hàng còn trong kho.
    /// </summary>
    public async Task<bool> CheckStockAsync(
        Guid productId,
        Guid shopId,
        int quantity,
        CancellationToken cancellationToken = default)
    {
        try
        {
            _logger.LogInformation(
                "EN: Checking stock / VI: Kiểm tra kho: Product={ProductId}, Shop={ShopId}, Quantity={Quantity}",
                productId, shopId, quantity);

            var response = await _httpClient.GetAsync(
                $"/api/v1/inventory/check?productId={productId}&shopId={shopId}&quantity={quantity}",
                cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                _logger.LogWarning("EN: Stock check failed / VI: Kiểm tra kho thất bại");
                return false;
            }

            var result = await response.Content.ReadFromJsonAsync<StockCheckResult>(cancellationToken);
            return result?.IsAvailable ?? false;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "EN: Error checking stock / VI: Lỗi khi kiểm tra kho");
            return false;
        }
    }

    /// <summary>
    /// EN: Deduct stock from inventory.
    /// VI: Trừ hàng khỏi kho.
    /// </summary>
    public async Task<bool> DeductStockAsync(
        Guid productId,
        Guid shopId,
        int quantity,
        CancellationToken cancellationToken = default)
    {
        try
        {
            _logger.LogInformation(
                "EN: Deducting stock / VI: Trừ kho: Product={ProductId}, Shop={ShopId}, Quantity={Quantity}",
                productId, shopId, quantity);

            var request = new DeductStockRequest(productId, shopId, quantity);
            var response = await _httpClient.PostAsJsonAsync(
                "/api/v1/inventory/deduct",
                request,
                cancellationToken);

            return response.IsSuccessStatusCode;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "EN: Error deducting stock / VI: Lỗi khi trừ kho");
            return false;
        }
    }
    /// <summary>
    /// EN: Deduct stock by inventory item ID (for recipe ingredients).
    /// VI: Trừ kho theo inventory item ID (cho nguyên liệu công thức).
    /// </summary>
    public async Task<bool> DeductStockByIdAsync(
        Guid inventoryItemId,
        int quantity,
        Guid? orderId = null,
        CancellationToken cancellationToken = default)
    {
        try
        {
            _logger.LogInformation(
                "EN: Deducting stock by ID / VI: Trừ kho theo ID: ItemId={ItemId}, Quantity={Quantity}",
                inventoryItemId, quantity);

            var request = new { inventoryItemId, amount = quantity, notes = "POS order deduction", referenceId = orderId };
            var response = await _httpClient.PostAsJsonAsync(
                "/api/v1/inventory/stock-out-by-id",
                request,
                cancellationToken);

            return response.IsSuccessStatusCode;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "EN: Error deducting stock by ID / VI: Lỗi trừ kho theo ID");
            return false;
        }
    }
}

public record StockCheckResult(bool IsAvailable, int AvailableQuantity);
public record DeductStockRequest(Guid ProductId, Guid ShopId, int Quantity);
