using BookHive.DTO.Loan;
using FastEndpoints;
using FluentValidation;

namespace BookHive.Validators.Loans;

public class CreateLoanDtoValidator : Validator<CreateLoanDto>
{
    public CreateLoanDtoValidator()
    {
        RuleFor(x => x.BookId)
            .GreaterThan(0)
            .WithMessage("Invalid book id.");

        RuleFor(x => x.MemberId)
            .GreaterThan(0)
            .WithMessage("Invalid member id.");

        RuleFor(x => x.LoanDate)
            .NotEmpty()
            .WithMessage("Date is required.");

        RuleFor(x => x.DueDate)
            .NotEmpty()
            .WithMessage("Due date is required.")
            .GreaterThan(d => d.LoanDate)
            .WithMessage("Due date must be in the future.")
            .Must((loan, dueDate) => dueDate <= loan.LoanDate.AddDays(30))
            .WithMessage("Due date must be in the future.");

        RuleFor(x => x.DueDate)
            .Must((dto, dueDate) =>
            {
                var dayOfWeek = dto.LoanDate.DayOfWeek;
                var isWeekend = dayOfWeek == DayOfWeek.Saturday
                                || dayOfWeek == DayOfWeek.Sunday;
                var maxDays = isWeekend ? 14 : 30;
                return dueDate <= dto.LoanDate.AddDays(maxDays);
            })
            .WithMessage("La durée max est de 14j (week-end) ou 30j (semaine).");
    }
}