using System.Security.Claims;
using FluentResults;
using MediatR;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Application.Queries.Concepts;

namespace NexusReader.Web.Services;

public class ServerConceptsMapService : IConceptsMapService
{
    private readonly IMediator _mediator;
    private readonly IIdentityService _identityService;

    public ServerConceptsMapService(
        IMediator mediator,
        IIdentityService identityService)
    {
        _mediator = mediator;
        _identityService = identityService;
    }

    public async Task<Result<BookConceptsMapResultDto>> GetConceptsMapAsync(Guid bookId)
    {
        try
        {
            var profileResult = await _identityService.GetProfileAsync();

            if (profileResult.IsFailed)
            {
                return Result.Fail<BookConceptsMapResultDto>("Użytkownik nie jest uwierzytelniony.");
            }

            var profile = profileResult.Value;
            var userId = profile.UserId;
            var tenantId = profile.TenantId.ToString();

            if (string.IsNullOrEmpty(userId))
            {
                return Result.Fail<BookConceptsMapResultDto>("Nie znaleziono identyfikatora użytkownika.");
            }

            return await _mediator.Send(new GetBookConceptsMapQuery(bookId, userId, tenantId));
        }
        catch (Exception ex)
        {
            return Result.Fail<BookConceptsMapResultDto>(new Error("Błąd pobierania mapy pojęć na serwerze.").CausedBy(ex));
        }
    }
}
