package com.eactive.eai.custom.alarm.ums.payload;

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

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;

public class ValidationUtil {
    private static final ValidatorFactory factory;
    private static final Validator validator;

    static {
        factory = Validation.byDefaultProvider()
                .configure()
                .messageInterpolator(new ParameterMessageInterpolator())
                .buildValidatorFactory();

        validator = factory.getValidator();
    }


    private ValidationUtil() {
    }


    public static <T> Set<ConstraintViolation<T>> validate(T target) {
        return validator.validate(target);
    }

    public static <T> void validateOrThrow(T target) {
        Set<ConstraintViolation<T>> violations = validate(target);
        if (!violations.isEmpty()) {
            String message = violations.stream()
                    .map(v -> v.getPropertyPath() + " : " + v.getMessage())
                    .collect(Collectors.joining(", "));
            throw new ConstraintViolationException("Validation failed: " + message, violations);
        }
    }

    public static <T> String getViolationMessage(T target) {
        Set<ConstraintViolation<T>> violations = validate(target);
        if (violations.isEmpty()) return null;
        return violations.stream()
                .map(v -> v.getPropertyPath() + " : " + v.getMessage())
                .collect(Collectors.joining(", "));
    }
}