package com.imprimelibros.erp.users.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.beans.PropertyDescriptor;

public class PasswordsMatchValidator implements ConstraintValidator<PasswordsMatch, Object> {
    private String passwordField;
    private String confirmPasswordField;

    @Override
    public void initialize(PasswordsMatch constraint) {
        this.passwordField = constraint.password();
        this.confirmPasswordField = constraint.confirmPassword();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        try {
            Object password = new PropertyDescriptor(passwordField, value.getClass())
                    .getReadMethod().invoke(value);
            Object confirm = new PropertyDescriptor(confirmPasswordField, value.getClass())
                    .getReadMethod().invoke(value);
            if (password == null && confirm == null) return true;
            return password != null && password.equals(confirm);
        } catch (Exception e) {
            return false;
        }
    }
}
