using FluentResults;
using MediatR;
using Microsoft.EntityFrameworkCore;
using NexusReader.Application.DTOs.User;
using NexusReader.Data.Persistence;

namespace NexusReader.Application.Queries.Library;

public record GetMyEbooksQuery(string UserId) : IRequest<Result<List<LastReadBookDto>>>;

public class GetMyEbooksQueryHandler : IRequestHandler<GetMyEbooksQuery, Result<List<LastReadBookDto>>>
{
    private readonly IDbContextFactory<AppDbContext> _dbContextFactory;

    public GetMyEbooksQueryHandler(IDbContextFactory<AppDbContext> dbContextFactory)
    {
        _dbContextFactory = dbContextFactory;
    }

    public async Task<Result<List<LastReadBookDto>>> Handle(GetMyEbooksQuery request, CancellationToken cancellationToken)
    {
        using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
        
        var ebooks = await dbContext.Ebooks
            .Where(e => e.UserId == request.UserId)
            .OrderByDescending(e => e.LastReadDate ?? e.AddedDate)
            .Select(e => new LastReadBookDto
            {
                Id = e.Id,
                Title = e.Title,
                Author = new AuthorDto 
                { 
                    Id = e.Author.Id, 
                    Name = e.Author.Name 
                },
                CoverUrl = e.CoverUrl,
                Progress = e.Progress,
                LastChapter = e.LastChapter ?? "Rozpoczynanie...",
                LastChapterIndex = e.LastChapterIndex,
                Description = e.Description,
                IsReadyForReading = e.IsReadyForReading
            })
            .ToListAsync(cancellationToken);

        return Result.Ok(ebooks);
    }
}
