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

import java.util.regex.Pattern;

/**
 * @description 邮箱校验方法
 * @filename EmailValidateMethod.java
 * @author yslg
 * @copyright yslg
 * @since 2025-11-02
 */
public class EmailValidateMethod implements ValidateMethod {
    
    // 邮箱正则表达式
    private static final Pattern EMAIL_PATTERN = Pattern.compile(
            "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
    );
    
    private final String[] allowedDomains; // 允许的域名列表
    
    /**
     * @description 默认构造函数，允许所有域名
     */
    public EmailValidateMethod() {
        this.allowedDomains = null;
    }
    
    /**
     * @description 限制域名的构造函数
     * @param allowedDomains 允许的域名列表，例如：["company.com", "example.com"]
     */
    public EmailValidateMethod(String[] allowedDomains) {
        this.allowedDomains = allowedDomains;
    }
    
    @Override
    public Boolean validate(Object value) {
        if (value == null || !(value instanceof String)) {
            return false;
        }
        
        String email = ((String) value).trim().toLowerCase();
        
        // 基本格式校验
        if (!EMAIL_PATTERN.matcher(email).matches()) {
            return false;
        }
        
        // 域名限制校验
        if (allowedDomains != null && allowedDomains.length > 0) {
            Boolean domainMatched = false;
            for (String domain : allowedDomains) {
                if (email.endsWith("@" + domain.toLowerCase())) {
                    domainMatched = true;
                    break;
                }
            }
            return domainMatched;
        }
        
        return true;
    }
    
    @Override
    public String getErrorMessage() {
        if (allowedDomains != null && allowedDomains.length > 0) {
            return "请输入有效的邮箱地址（仅支持: " + String.join(", ", allowedDomains) + "）";
        }
        return "请输入有效的邮箱地址";
    }
    
    @Override
    public String getName() {
        return "邮箱校验";
    }
}

