using BookHive.DTO.Review;
using BookHive.Models;
using BookHive.Repositories;
using BookHive.Specifications.Books;
using BookHive.Specifications.Reviews;
using FastEndpoints;

namespace BookHive.Endpoints.Reviews;

public class ReviewRequest
{
    public int BookId { get; set; }
}

public class GetReviewEndpoint(BookRepository bookRepository, ReviewRepository reviewRepository) : Endpoint<ReviewRequest, List<GetReviewDto>>
{
    public override void Configure()
    {
        Get("/books/{@BookId}/reviews", x => new { x.BookId });
        AllowAnonymous();
    }

    public override async Task HandleAsync(ReviewRequest req, CancellationToken ct)
    {
        Book? book = await bookRepository.SingleOrDefaultAsync(new GetBookByIdSpec(req.BookId), ct);

        if (book is null)
        {
            await Send.NoContentAsync(ct);
            return;
        }

        await Send.OkAsync(await reviewRepository.ProjectToListAsync<GetReviewDto>(new GetReviewByBookIdSpec(req.BookId), ct), ct);
    }
}