Files
FACULTATE-HEALTHCARE_MANAGER/backend/Application/Endpoints/Patients/ModifyPatient/PatientProfileValidator.cs
T
2024-05-30 15:40:13 +03:00

55 lines
2.5 KiB
C#

using Application.Services.Database.PostgreSQL;
using FluentValidation;
namespace Application.Endpoints.Patients.ModifyPatient;
public class PatientProfileValidator : AbstractValidator<ModifyPatientCommand>
{
private readonly IAdminRepository _adminRepository;
private readonly IDoctorRepository _doctorRepository;
private readonly IPatientRepository _patientRepository;
public PatientProfileValidator(IPatientRepository patientRepository,
IDoctorRepository doctorRepository, IAdminRepository adminRepository)
{
_patientRepository = patientRepository;
_doctorRepository = doctorRepository;
_adminRepository = adminRepository;
RuleFor(x => x.Id)
.NotEmpty().WithMessage("Id is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(IsPatientRegistered).WithMessage("Patient is not registered in system")
.WithErrorCode(HttpStatusCodes.NotFound.ToString());
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 in use by another patient.")
.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());
}
private async Task<bool> IsPatientRegistered(Guid id, CancellationToken token)
{
var patient = await _patientRepository.GetByIdAsync(id, token);
return patient != null;
}
private async Task<bool> BeUniqueEmail(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 doctor == null && admin == null;
}
}