using Application.Services.Database;
using FluentValidation;

namespace Application.Endpoints.Patients.Registration;

public class PatientRegistrationValidation : AbstractValidator<PatientRegistrationDto>
{
    private readonly IPatientRepository _patientRepository;

    public PatientRegistrationValidation(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(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());
    }

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