using System.Net.Http.Json;
using Domain.Dtos.Stock;
using Domain.Generics;

public class StockScanService : IStockScanService
{
    private readonly HttpClient _http;

    public StockScanService(HttpClient http)
    {
        _http = http;
    }
    /// <summary>
    /// Envía el RAW al backend (parsea + busca) y devuelve el primer match mapeado a la UI.
    /// </summary>
    public async Task<StockItemSelectionDto?> ParseAndMatchAsync(string rawInput, int locationId)
    {
        if (string.IsNullOrWhiteSpace(rawInput))
            return null;

        var payload = new StockScanRawRequest(rawInput, locationId, Page: 1, PageSize: 10);

        using var resp = await _http.PostAsJsonAsync("/api/lsstockscan/parse-and-search", payload);
        if (!resp.IsSuccessStatusCode)
            return null;

        var pr = await resp.Content.ReadFromJsonAsync<PagedResult<StockItemScanResultDto>>();
        var first = pr?.Items?.FirstOrDefault();
        if (first is null) return null;

        return new StockItemSelectionDto
        {
            StockItemId = first.StockItemId,
            ProductId = first.ProductId,
            ProductName = first.ProductName,
            Batch = first.Batch ?? string.Empty,
            Expiration = first.Expiration?.ToDateTime(TimeOnly.MinValue),
            Quantity = first.AvailableQty,
            LocationId = first.LocationId ?? locationId,
            TraceabilityType = first.TraceabilityType,
            Serial = first.Serial ?? string.Empty
        };
    }
}
