using BookHive.DTO.Loan;
using BookHive.Models;
using BookHive.Repositories;
using BookHive.Specifications.Books;
using BookHive.Specifications.Loans;
using BookHive.Specifications.Members;
using FastEndpoints;

namespace BookHive.Endpoints.Loans;

public class CreateLoanEndpoint(LoanRepository loanRepository, BookRepository bookRepository, MemberRepository memberRepository, AutoMapper.IMapper mapper)
    : Endpoint<CreateLoanDto>
{
    public override void Configure()
    {
        Post("/loans/");
        AllowAnonymous();
    }

    public override async Task HandleAsync(CreateLoanDto 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;
        }

        Loan? loan = await loanRepository.FirstOrDefaultAsync(new GetAvailableBookByIdSpec(req.BookId), ct);
        if (loan is not null)
        {
            await Send.StringAsync("Ce livre est déjà emprunté", 400, cancellation: ct);
            return;
        }

        if (req.DueDate < req.LoanDate || req.DueDate.DayNumber - req.LoanDate.DayNumber < 1 || req.DueDate.DayNumber - req.LoanDate.DayNumber > 30)
        {
            await Send.StringAsync("La date de retour estimée est incorrecte", 400, cancellation: ct);
            return;
        }

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