package cn.nianxx.thhotel.platform.message.service.impl;

import java.util.regex.Pattern;
import org.springframework.stereotype.Component;

/**
 * 来源消息安全摘要工具。正文和主题仍做安全摘要；发件人展示值只清理首尾空白。
 */
@Component
public class SourceMessageSafetySanitizer {

    private static final int MAX_SNIPPET_LENGTH = 200;
    private static final Pattern EMAIL_PATTERN = Pattern.compile(
            "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}");
    private static final Pattern URL_PATTERN = Pattern.compile("https?://\\S+");
    private static final Pattern LONG_DIGIT_PATTERN = Pattern.compile("\\d{8,}");
    private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");

    /**
     * 生成发送人展示值。业务人员需要识别邮件真实发件人，因此这里只清理首尾空白，不再打码。
     */
    String senderSummary(String senderIdentifier) {
        return trimToEmpty(senderIdentifier);
    }

    /**
     * 生成可展示短摘要，统一替换邮箱、URL 和长数字等敏感片段。
     */
    String safeSnippet(String textBody) {
        String normalized = WHITESPACE_PATTERN.matcher(trimToEmpty(textBody)).replaceAll(" ");
        String withoutUrls = URL_PATTERN.matcher(normalized).replaceAll("[url]");
        String withoutEmails = EMAIL_PATTERN.matcher(withoutUrls).replaceAll("[email]");
        String withoutLongDigits = LONG_DIGIT_PATTERN.matcher(withoutEmails).replaceAll("[number]");
        if (withoutLongDigits.length() <= MAX_SNIPPET_LENGTH) {
            return withoutLongDigits;
        }
        return withoutLongDigits.substring(0, MAX_SNIPPET_LENGTH);
    }

    /**
     * 将空值转换为空字符串，并清理首尾空白，方便后续脱敏规则处理。
     */
    private String trimToEmpty(String value) {
        return value == null ? "" : value.trim();
    }
}
