// EN: HTTP client for F&B Engine.
// VI: HTTP client cho F&B Engine.

namespace OrderService.API.Infrastructure.HttpClients;

/// <summary>
/// EN: Client for calling F&amp;B Engine for kitchen operations.
/// VI: Client gọi F&amp;B Engine để thực hiện thao tác bếp.
/// </summary>
public class FnbEngineClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<FnbEngineClient> _logger;

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

    /// <summary>
    /// EN: Create kitchen ticket for prepared food.
    /// VI: Tạo phiếu bếp cho món ăn.
    /// </summary>
    public async Task<Guid?> CreateKitchenTicketAsync(
        Guid productId,
        string productName,
        Guid shopId,
        int quantity,
        string? notes,
        CancellationToken cancellationToken = default)
    {
        try
        {
            _logger.LogInformation(
                "EN: Creating kitchen ticket / VI: Tạo phiếu bếp: {ProductName}, Quantity: {Quantity}",
                productName, quantity);

            var request = new CreateKitchenTicketRequest(
                productId,
                productName,
                shopId,
                quantity,
                notes);

            var response = await _httpClient.PostAsJsonAsync(
                "/api/v1/kitchen/tickets",
                request,
                cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                _logger.LogWarning("EN: Failed to create kitchen ticket / VI: Tạo phiếu bếp thất bại");
                return null;
            }

            var result = await response.Content.ReadFromJsonAsync<CreateKitchenTicketResult>(cancellationToken);
            return result?.TicketId;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "EN: Error creating kitchen ticket / VI: Lỗi khi tạo phiếu bếp");
            return null;
        }
    }

    /// <summary>
    /// EN: Get recipe by product ID and shop ID for inventory deduction.
    /// VI: Lấy công thức theo product ID và shop ID để trừ kho.
    /// </summary>
    public async Task<RecipeWithIngredientsResult?> GetRecipeByProductAsync(
        Guid productId,
        Guid shopId,
        CancellationToken cancellationToken = default)
    {
        try
        {
            var response = await _httpClient.GetAsync(
                $"/api/v1/kitchen/recipes/by-product?productId={productId}&shopId={shopId}",
                cancellationToken);

            if (!response.IsSuccessStatusCode) return null;

            var wrapper = await response.Content.ReadFromJsonAsync<ApiResponseWrapper<RecipeWithIngredientsResult>>(cancellationToken);
            return wrapper?.Data;
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "EN: Failed to get recipe / VI: Không lấy được công thức: Product={ProductId}", productId);
            return null;
        }
    }
}

public record CreateKitchenTicketRequest(
    Guid ProductId,
    string ProductName,
    Guid ShopId,
    int Quantity,
    string? Notes);

public record CreateKitchenTicketResult(Guid TicketId);

public record RecipeWithIngredientsResult(
    Guid Id, Guid ProductId, Guid ShopId, string Name,
    List<RecipeIngredientResult> Ingredients);

public record RecipeIngredientResult(
    Guid Id, string IngredientName, decimal Quantity, string Unit, decimal CostPerUnit,
    Guid? InventoryItemId, decimal QuantityPerServing);

public record ApiResponseWrapper<T>(bool Success, T? Data, string? Error);
