using Application.Services.Database;
using FluentValidation;

namespace Application.Endpoints.Doctors.ResetPassword;

public class DoctorResetPasswordValidation : AbstractValidator<DoctorResetPasswordDto>
{
    private readonly IDoctorRepository _doctorRepository;

    public DoctorResetPasswordValidation(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(BeExistingDoctor).WithMessage("Doctor with this email does not exist.")
            .WithErrorCode(HttpStatusCodes.NotFound.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())
            .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<bool> BeExistingDoctor(string email, CancellationToken cancellationToken)
    {
        var doctor = await _doctorRepository.FindByEmailAsync(email);
        return doctor != null;
    }

    private async Task<bool> BeDifferentFromOldPassword(string email, string newPassword,
        CancellationToken cancellationToken)
    {
        var currentDoctor = await _doctorRepository.FindByEmailAsync(email);
        return !newPassword.Equals(currentDoctor?.Password, StringComparison.Ordinal);
    }
}