package me.qwq.doghouse.validator;

import java.net.Proxy;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import me.qwq.doghouse.entity.config.NetworkConfig;
import me.qwq.doghouse.util.IPUtils;

public class NetworkConfigValidator implements IValidator, ConstraintValidator<NetworkConfigValid, NetworkConfig> {

    @Override
    public boolean isValid(NetworkConfig value, ConstraintValidatorContext context) {
        
        if (value == null) return false;
        if (!(value instanceof NetworkConfig networkConfig)) return false;
        
        if (networkConfig.getProxyType() != null && networkConfig.getProxyType() != Proxy.Type.DIRECT) {
            if (StringUtils.isBlank(networkConfig.getProxyHost())) {
                return invalid(context, "设置代理为 HTTP 或 SOCKS 时，代理地址不允许为空");
            }
            if (Objects.isNull(networkConfig.getProxyPort()) || networkConfig.getProxyPort() <= 0 || networkConfig.getProxyPort() > 65535) {
                return invalid(context, "端口不合法");
            }
            // 不做连通性校验：有的代理可能先添加后生效
        }
        
        // 校验 trustedIPv4、IPv6 或 CIDR
        List<String> trustedList = networkConfig.getTrustedProxiesList();
        for (String trusted : trustedList) {
            if (!IPUtils.isValidIPOrCIDR(trusted)) {
                return invalid(context, "非法的 IPv4/IPv6 或 CIDR: " + trusted);
            }
        }
        
        return true;
        
    }

}
