package cn.novalon.gym.manage.sys.primitive;

import cn.novalon.gym.manage.common.exception.ErrorCode;
import cn.novalon.gym.manage.common.exception.ValidationException;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Pattern;

/**
 * 邮箱值对象
 * 
 * @author 张翔
 * @date 2026-03-13
 */
public final class Email {

    private static final Pattern EMAIL_PATTERN = Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");

    private final String value;

    public String getValue() {
        return value;
    }

    private Email(String value) {
        this.value = value;
    }

    public static Email of(String value) {
        if (StringUtils.isBlank(value)) {
            throw new ValidationException(ErrorCode.VALIDATION_REQUIRED, "Email is required");
        }
        validate(value);
        return new Email(value);
    }

    public static Email ofNullable(String value) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        validate(value);
        return new Email(value);
    }

    private static void validate(String value) {
        if (!EMAIL_PATTERN.matcher(value).matches()) {
            throw new ValidationException(ErrorCode.VALIDATION_INVALID_FORMAT, "Invalid email format");
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Email email = (Email) o;
        return value.equals(email.value);
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

    @Override
    public String toString() {
        return value;
    }
}
