package com.face.global.validator.impl;


import com.face.global.validator.enums.EnumCheck;
import com.face.util.SystemExceptionUtils;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 枚举验证器实现
 */
@Slf4j
public class EnumConstraintValidator implements ConstraintValidator<EnumCheck, Object> {
    /**
     * 注解对象
     */
    private EnumCheck annotation;

    /**
     * 初始化方法
     *
     * @param constraintAnnotation 注解对象
     */
    @Override
    public void initialize(EnumCheck constraintAnnotation) {
        this.annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (Objects.isNull(value)) {
            return true;
        }
        Object[] enumConstants = annotation.clazz().getEnumConstants();
        try {
            // 核心代码实现
            Method method = annotation.clazz().getMethod(annotation.method());
            for (Object enumConstant : enumConstants) {
                if (value.equals(method.invoke(enumConstant))) {
                    return true;
                }
            }

        } catch (Exception e) {
            log.error("validEnumFail", e);
            throw SystemExceptionUtils.buildBusinessException("validEnumFail");
        }
        return false;
    }
}