package io.github.shirainbown.sharelink.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

/**
 * Email normalization and hashing helpers shared by the verification flow.
 */
public final class EmailUtils {

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

    private EmailUtils() {
    }

    /**
     * Normalizes an email address (trimmed, lower-cased).
     *
     * @return the normalized email, or {@code null} when blank
     */
    public static String normalizeEmail(String email) {
        if (email == null) {
            return null;
        }
        var normalized = email.trim().toLowerCase(Locale.ROOT);
        return StringUtils.isBlank(normalized) ? null : normalized;
    }

    public static boolean isValidEmail(String email) {
        return email != null && EMAIL_PATTERN.matcher(email).matches();
    }

    /**
     * SHA-256 hex of the given value; used as the deterministic metadata name of
     * {@code VerifiedDownloader} (and the comment plugin's {@code VerifiedCommenter}).
     */
    public static String sha256Hex(String value) {
        try {
            var digest = MessageDigest.getInstance("SHA-256");
            return HexFormat.of()
                .formatHex(digest.digest(value.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-256 algorithm is unavailable", e);
        }
    }
}
