using System;
using System.Threading;
using System.Threading.Tasks;
using FluentResults;
using MediatR;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Application.DTOs.AI;

namespace NexusReader.Application.Queries.Library;

public record AskLibraryQuestionQuery(string Question, string TenantId, Guid? EbookId = null, int Limit = 5) 
    : IRequest<Result<GroundedResponseDto>>;

public class AskLibraryQuestionQueryHandler : IRequestHandler<AskLibraryQuestionQuery, Result<GroundedResponseDto>>
{
    private readonly IKnowledgeService _knowledgeService;
    
    public AskLibraryQuestionQueryHandler(IKnowledgeService knowledgeService)
    {
        _knowledgeService = knowledgeService;
    }

    public async Task<Result<GroundedResponseDto>> Handle(AskLibraryQuestionQuery request, CancellationToken cancellationToken)
    {
        if (string.IsNullOrWhiteSpace(request.Question))
        {
            return Result.Fail("Question cannot be empty.");
        }

        return await _knowledgeService.AskQuestionAsync(
            request.Question, 
            request.TenantId, 
            request.EbookId, 
            request.Limit, 
            cancellationToken);
    }
}
