using System.Net.Http.Json;
using FluentResults;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Application.Queries.Concepts;

namespace NexusReader.Web.Client.Services;

public class WasmConceptsMapService : IConceptsMapService
{
    private readonly HttpClient _httpClient;

    public WasmConceptsMapService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<Result<BookConceptsMapResultDto>> GetConceptsMapAsync(Guid bookId)
    {
        try
        {
            var response = await _httpClient.GetAsync($"api/book/{bookId}/concepts-map");
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadFromJsonAsync<BookConceptsMapResultDto>();
                return result != null ? Result.Ok(result) : Result.Fail<BookConceptsMapResultDto>("Błąd deserializacji mapy pojęć.");
            }

            var errorContent = await response.Content.ReadAsStringAsync();
            return Result.Fail<BookConceptsMapResultDto>($"Błąd serwera ({response.StatusCode}): {errorContent}");
        }
        catch (Exception ex)
        {
            return Result.Fail<BookConceptsMapResultDto>(new Error("Błąd sieci przy pobieraniu mapy pojęć.").CausedBy(ex));
        }
    }
}
