package com.seer.teach.common.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 * NotAllNull 注解的验证器实现
 */
public class NotAllNullValidator implements ConstraintValidator<NotAllNull, Object> {

    private List<String> fieldNames;

    @Override
    public void initialize(NotAllNull annotation) {
        fieldNames = Arrays.asList(annotation.value());
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        if (object == null) {
            return true; // Let @NotNull handle null objects
        }

        try {
            for (String fieldName : fieldNames) {
                Field field = object.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Object value = field.get(object);
                if (value != null) {
                    // 只要有一个字段不为空，就验证通过
                    return true;
                }
            }
            // 所有字段都为空，验证不通过
            return false;
        } catch (Exception e) {
            // 如果出现异常，认为验证不通过
            return false;
        }
    }
}