using System.Text.Json;
using Bimix.Application.DTOModels;
using Bimix.Application.DTOModels.Common;
using Microsoft.AspNetCore.WebUtilities;

namespace Bimix.UI.Shared.Services;

public class ProductService(HttpClient httpClient)
{
    private readonly HttpClient _httpClient = httpClient;
    private readonly JsonSerializerOptions _jsonOptions = new()
    {
        PropertyNameCaseInsensitive = true
    };

    public async Task<PagedResult<ProductDto>> GetProductsAsync(ProductFilterRequest request)
    {
        var queryParams = new Dictionary<string, string?>
        {
            ["page"] = request.Page.ToString(),
            ["pageSize"] = request.PageSize.ToString(),
        };

        if (!string.IsNullOrWhiteSpace(request.Search))
        {
            queryParams["search"] = request.Search;
        }
        if (!string.IsNullOrWhiteSpace(request.Name))
        {
            queryParams["name"] = request.Name;
        }
        if (!string.IsNullOrWhiteSpace(request.Code))
        {
            queryParams["code"] = request.Code;
        }

        if (!string.IsNullOrWhiteSpace(request.Ean))
        {
            queryParams["ean"] = request.Ean;
        }

        var uri = QueryHelpers.AddQueryString("api/products", queryParams);
        var response = await _httpClient.GetAsync(uri);
        
        response.EnsureSuccessStatusCode();
        
        var json = await response.Content.ReadAsStringAsync();
        var result = JsonSerializer.Deserialize<PagedResult<ProductDto>>(json, _jsonOptions);
        
        return result ?? new PagedResult<ProductDto>();
    }
}