package com.eactive.testmaster.common.validator;

import com.eactive.testmaster.api.repository.MockRouteRepository;
import com.eactive.testmaster.common.util.ApplicationContextUtil;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.beanutils.PropertyUtils;

public class UniqueRouteValidator implements ConstraintValidator<UniqueRoute, Object> {

    private String method;

    private String path;

    @Override
    public void initialize(UniqueRoute constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        this.method = constraintAnnotation.method();
        this.path = constraintAnnotation.path();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        String methodValue;
        String pathValue;
        try {
            methodValue = (String) PropertyUtils.getProperty(value, this.method);
            pathValue = (String) PropertyUtils.getProperty(value, this.path);
        } catch (Exception e) {
            return false;
        }
        MockRouteRepository mockRouteRepository = ApplicationContextUtil.getContext().getBean(MockRouteRepository.class);
        long found = mockRouteRepository.countByMethodAndPathPattern(methodValue, pathValue);

        String message = "등록된 API가 존재합니다.";

        if (found > 0L){
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(message)
                    .addPropertyNode(this.path)
                    .addConstraintViolation();

            return false;
        }

        return true;
    }
}
