using BookHive.DTO.Book;
using BookHive.Models;
using BookHive.Repositories;
using BookHive.Specifications.Books;
using FastEndpoints;

namespace BookHive.Endpoints.Books;

public class UpdateBookEndpoit(BookRepository bookRepository, AutoMapper.IMapper mapper) : Endpoint<UpdateBookDto>
{
    public override void Configure()
    {
        Put("/books/{@Id}/", x => new { x.Id });
        AllowAnonymous();
    }

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

        mapper.Map(req, book);
        await bookRepository.SaveChangesAsync(ct);
        await Send.NoContentAsync(ct);
    }
}