package de.htwsaar.webshop.service.impl;

import de.htwsaar.webshop.service.ValidatorService;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
@Slf4j
public class ValidatorServiceImpl implements ValidatorService {
    private final Validator validator;

    public ValidatorServiceImpl() {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * Jakarta Validator
     *
     * @param validatable any Validatable
     * @param <T>         any Validatable
     * @return whether the Object is Invalid
     */
    @Override
    public <T> boolean isInvalid(T validatable) {
        Set<ConstraintViolation<T>> violations = validator.validate(validatable);
        violations.forEach((violation) -> log.warn("[Validator] Invalid {}:  {}", validatable, violation.getMessage()));
        return !violations.isEmpty();
    }
}
