using Application.Services.Database.PostgreSQL; using Application.Services.HashingAlgorithms; using Domain; using FluentValidation; namespace Application.Endpoints.Authorization.UserRegister; public class UserRegisterValidator : AbstractValidator { private readonly IAdminRepository _adminRepository; private readonly IDoctorRepository _doctorRepository; private readonly IPatientRepository _patientRepository; public UserRegisterValidator(IPatientRepository patientRepository, IDoctorRepository doctorRepository, IAdminRepository adminRepository) { _patientRepository = patientRepository; _doctorRepository = doctorRepository; _adminRepository = adminRepository; RuleFor(x => x.Name) .NotEmpty().WithMessage("Name is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .MaximumLength(30).WithMessage("Maximum name length of 30 characters") .WithErrorCode(HttpStatusCodes.BadRequest.ToString()); RuleFor(x => x.Email) .NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .MustAsync(async (email, token) => await AccountNotRegistered(email, token)) .WithMessage("Account already registered in system.").WithErrorCode(HttpStatusCodes.BadRequest.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.Role) .NotEmpty().WithMessage("Role is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .Must(BeAValidRole).WithMessage("Invalid role specified.") .WithErrorCode(HttpStatusCodes.BadRequest.ToString()); } private bool BeAValidRole(string role) { var validRoles = new[] { UserRoles.Admin, UserRoles.Doctor, UserRoles.Patient }; return validRoles.Contains(role); } private async Task AccountNotRegistered(string email, CancellationToken token) { var patient = await _patientRepository.FindByEmailAsync(email, token); var doctor = await _doctorRepository.FindByEmailAsync(email, token); var admin = await _adminRepository.FindByEmailAsync(email, token); return patient == null && doctor == null && admin == null; } }