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

namespace BookHive.Endpoints.Reviews;

public class CreateReviewEndpoint(
    ReviewRepository reviewRepository,
    MemberRepository memberRepository,
    BookRepository bookRepository,
    AutoMapper.IMapper mapper)
    : Endpoint<CreateReviewDto>
{
    public override void Configure()
    {
        Post("/books/{@BookId}/reviews/", x => new { x.BookId });
        AllowAnonymous();
    }

    public override async Task HandleAsync(CreateReviewDto req, CancellationToken ct)
    {
        Book? book = await bookRepository.SingleOrDefaultAsync(new GetBookByIdSpec(req.BookId), ct);
        if (book is null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }

        Member? member = await memberRepository.SingleOrDefaultAsync(new GetMemberByIdSpec(req.MemberId), ct);
        if (member is null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }

        if (!member.IsActive)
        {
            await Send.StringAsync("Le membre est désactivé", 400, cancellation: ct);
            return;
        }

        Review? review = await reviewRepository.SingleOrDefaultAsync(new GetReviewByCriteriaSpec(req.BookId, req.MemberId), ct);
        if (review is not null)
        {
            await Send.StringAsync("Le membre a déjà posté un commentaire", 400, cancellation: ct);
            return;
        }

        await reviewRepository.AddAsync(mapper.Map<Review>(req), ct);
        await Send.NoContentAsync(ct);
    }
}