using BookHive.Models;
using BookHive.Repositories;
using BookHive.Specifications.Authors;
using FastEndpoints;

namespace BookHive.Endpoints.Authors;

public class DeleteAuthorRequest
{
    public int Id { get; set; }
}

public class DeleteAuthorEndpoint(AuthorRepository authorRepository) : Endpoint<DeleteAuthorRequest>
{
    public override void Configure()
    {
        Delete("/authors/{@Id}", x => new { x.Id });
        AllowAnonymous();
    }

    public override async Task HandleAsync(DeleteAuthorRequest req, CancellationToken ct)
    {
        Author? author = await authorRepository.SingleOrDefaultAsync(new GetAuthorByIdSpec(req.Id), ct);

        if (author is null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }

        if (author.Books?.Count > 0)
        {
            await Send.StringAsync("L'auteur possède encore des livres", 409, cancellation: ct);
            return;
        }

        await authorRepository.DeleteAsync(author, ct);
        await Send.NoContentAsync(ct);
        ;
    }
}