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

namespace BimAI.UI.Shared.Services;

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

    public async Task<PagedResult<InvoiceDto>> GetInvoiceAsync(InvoiceFilterRequest 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/invoice", queryParams);
        Console.WriteLine($"========== InvoiceService - Full URL: {_httpClient.BaseAddress}{uri} ==========");

        var response = await _httpClient.GetAsync(uri);
        Console.WriteLine($"========== InvoiceService - Response status: {response.StatusCode} ==========");

        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"========== InvoiceService - Error response: {errorContent} ==========");
        }

        response.EnsureSuccessStatusCode();

        var json = await response.Content.ReadAsStringAsync();
        Console.WriteLine($"========== InvoiceService - Response JSON length: {json.Length} ==========");
        Console.WriteLine($"========== InvoiceService - Response JSON: {json.Substring(0, Math.Min(500, json.Length))} ==========");

        var result = JsonSerializer.Deserialize<PagedResult<InvoiceDto>>(json, _jsonOptions);
        Console.WriteLine($"========== InvoiceService - Deserialized result - Items count: {result?.Items?.Count ?? 0}, Total: {result?.TotalCount ?? 0} ==========");

        return result ?? new PagedResult<InvoiceDto>();
    }
}