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

namespace BookHive.Endpoints.Loans;

public class PatchReturnLoanRequest
{
    public int Id { get; set; }
    public DateOnly ReturnDate { get; set; }
}

public class PatchReturnLoanEndpoint(LoanRepository loanRepository) : Endpoint<PatchReturnLoanRequest>
{
    public override void Configure()
    {
        Patch("/loans/{@Id}/return/", x => new { x.Id });
        AllowAnonymous();
    }

    public override async Task HandleAsync(PatchReturnLoanRequest req, CancellationToken ct)
    {
        Loan? loan = await loanRepository.SingleOrDefaultAsync(new GetLoanByIdSpec(req.Id), ct);
        if (loan is null)
        {
            await Send.NotFoundAsync(ct);
            return;
        }

        loan?.ReturnDate = req.ReturnDate;
        await loanRepository.SaveChangesAsync(ct);
        await Send.NoContentAsync(ct);
    }
}