using Application.Services.Database; using FluentValidation; namespace Application.Endpoints.Patients.ResetPassword; public class PatientResetPasswordValidation : AbstractValidator { private readonly IPatientRepository _patientRepository; public PatientResetPasswordValidation(IPatientRepository patientRepository) { _patientRepository = patientRepository; RuleFor(x => x.Email) .NotEmpty().WithMessage("Email is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .EmailAddress().WithMessage("Invalid email format.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .MustAsync(BeExistingPacient).WithMessage("Patient with this email does not exist.") .WithErrorCode(HttpStatusCodes.NotFound.ToString()); RuleFor(x => x.Password) .NotEmpty().WithMessage("Password is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString()) .MustAsync((dto, password, context, cancellationToken) => BeDifferentFromOldPassword(dto.Email, password, cancellationToken)) .WithMessage("New password cannot be the same as old password.") .WithErrorCode(HttpStatusCodes.BadRequest.ToString()); } private async Task BeExistingPacient(string email, CancellationToken cancellationToken) { var pacient = await _patientRepository.FindByEmailAsync(email); return pacient != null; } private async Task BeDifferentFromOldPassword(string email, string newPassword, CancellationToken cancellationToken) { var currentPatient = await _patientRepository.FindByEmailAsync(email); return !newPassword.Equals(currentPatient?.Password, StringComparison.Ordinal); } }