package org.eco.common.core.utils;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eco.common.core.exception.base.BaseException;

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

/**
 * Validator 校验框架工具
 *
 * @author wgk
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ValidatorUtils {

    private static final Validator VALID = SpringUtils.getBean(Validator.class);

    public static <T> void validate(T object, Class<?>... groups) {
        Set<ConstraintViolation<T>> validate = VALID.validate(object, groups);
        if (!validate.isEmpty()) {
            validate.forEach(constraintViolation -> log.error(constraintViolation.getMessage()));
            String msg = validate.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(","));
            throw new BaseException("参数校验异常: {}", msg);
        }
    }

}
