using Application.Services.Database;
using FluentValidation;

namespace Application.Endpoints.Doctors.Registration;

public class DoctorRegistrationValidation : AbstractValidator<DoctorRegistrationDto>
{
    private readonly IDoctorRepository _doctorRepository;

    public DoctorRegistrationValidation(IDoctorRepository doctorRepository)
    {
        _doctorRepository = doctorRepository;

        RuleFor(x => x.Email)
            .NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
            .EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
            .MustAsync(BeUniqueEmail).WithMessage("Email already exists.")
            .WithErrorCode(HttpStatusCodes.Conflict.ToString());

        RuleFor(x => x.Password)
            .NotEmpty().WithMessage("Password is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
            .MinimumLength(8).WithMessage("Password must be at least 8 characters long.")
            .WithErrorCode(HttpStatusCodes.BadRequest.ToString());

        RuleFor(x => x.Name)
            .NotEmpty().WithMessage("Name is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
            .MinimumLength(3).WithMessage("Name must be at least 3 characters long.")
            .WithErrorCode(HttpStatusCodes.BadRequest.ToString());

        RuleFor(x => x.Description)
            .MaximumLength(3000).WithMessage("Description must not exceed 3000 characters.")
            .WithErrorCode(HttpStatusCodes.BadRequest.ToString());
    }

    private async Task<bool> BeUniqueEmail(string email, CancellationToken cancellationToken)
    {
        var doctor = await _doctorRepository.FindByEmailAsync(email);
        return doctor == null;
    }
}