using FluentResults;
using NexusReader.Application.Abstractions.Messaging;
using NexusReader.Application.Abstractions.Services;

namespace NexusReader.Application.Queries.Graph;

internal sealed class GetKnowledgeGraphQueryHandler : IQueryHandler<GetKnowledgeGraphQuery, GraphDataDto>
{
    private readonly IKnowledgeService _knowledgeService;

    public GetKnowledgeGraphQueryHandler(IKnowledgeService knowledgeService)
    {
        _knowledgeService = knowledgeService;
    }

    public async Task<Result<GraphDataDto>> Handle(GetKnowledgeGraphQuery request, CancellationToken cancellationToken)
    {
        if (string.IsNullOrWhiteSpace(request.Text))
            return Result.Ok(new GraphDataDto());

        var result = await _knowledgeService.GetGraphDataAsync(
            request.Text, 
            request.TenantId, 
            ebookId: request.EbookId, 
            cancellationToken: cancellationToken);

        if (result.IsFailed)
            return Result.Fail<GraphDataDto>(result.Errors);

        var graph = result.Value.Graph;

        return graph is null ? Result.Ok(new GraphDataDto()) : Result.Ok(graph);
    }
}
