package com.greenorange.promotion.annotation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 初始化时从 enumClass 拿到所有常量的 getValue()，
 * 然后在 isValid 中判断传入值是否包含于其中。
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, String> {
    private Set<String> validValues;

    @Override
    public void initialize(EnumValue annotation) {
        Class<? extends BaseEnum> enumClass = annotation.enumClass();
        validValues = Stream.of(enumClass.getEnumConstants())
                            .map(BaseEnum::getValue)
                            .collect(Collectors.toSet());
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return StringUtils.isBlank(value) || validValues.contains(value);
    }
}
