package org.xyzh.common.utils.validation.method;

import java.util.regex.Pattern;

/**
 * @description URL校验方法
 * @filename UrlValidateMethod.java
 * @author yslg
 * @copyright yslg
 * @since 2025-11-02
 */
public class UrlValidateMethod implements ValidateMethod {
    
    // URL正则表达式
    private static final Pattern URL_PATTERN = Pattern.compile(
            "^(https?|ftp)://[a-zA-Z0-9+&@#/%?=~_|!:,.;-]*[a-zA-Z0-9+&@#/%=~_|-]$"
    );
    
    private final Boolean requireHttps; // 是否要求HTTPS
    
    public UrlValidateMethod() {
        this.requireHttps = false;
    }
    
    public UrlValidateMethod(Boolean requireHttps) {
        this.requireHttps = requireHttps;
    }
    
    @Override
    public Boolean validate(Object value) {
        if (value == null || !(value instanceof String)) {
            return false;
        }
        
        String url = ((String) value).trim();
        
        // 基本格式校验
        if (!URL_PATTERN.matcher(url).matches()) {
            return false;
        }
        
        // HTTPS校验
        if (requireHttps && !url.startsWith("https://")) {
            return false;
        }
        
        return true;
    }
    
    @Override
    public String getErrorMessage() {
        return requireHttps ? "请输入有效的HTTPS链接" : "请输入有效的URL";
    }
    
    @Override
    public String getName() {
        return "URL校验";
    }
}

