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

import cn.nianxx.thhotel.platform.message.service.SourceMessageHtmlSanitizerService;
import java.util.regex.Pattern;
import org.springframework.stereotype.Service;

/**
 * SourceMessage HTML 清洗服务实现。第一版使用白盒正则策略，后续可替换为专用 HTML sanitizer。
 */
@Service
public class SourceMessageHtmlSanitizerServiceImpl implements SourceMessageHtmlSanitizerService {

    private static final String HTML_RENDER_MODE_SANITIZED = "SANITIZED_HTML";
    private static final String HTML_RENDER_MODE_TEXT_ONLY = "TEXT_ONLY";
    private static final Pattern DANGEROUS_TAG_PATTERN = Pattern.compile(
            "(?is)<\\s*(script|style|iframe|object|embed|meta|link|base|form)[^>]*>.*?<\\s*/\\s*\\1\\s*>"
                    + "|<\\s*(script|style|iframe|object|embed|meta|link|base|form)[^>]*/?\\s*>");
    private static final Pattern EVENT_ATTRIBUTE_PATTERN = Pattern.compile(
            "(?i)\\s+on[a-z0-9_-]+\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]+)");
    private static final Pattern STYLE_ATTRIBUTE_PATTERN = Pattern.compile(
            "(?i)\\s+style\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]+)");
    private static final Pattern DANGEROUS_URL_ATTRIBUTE_PATTERN = Pattern.compile(
            "(?i)\\s+(href|src|xlink:href|formaction)\\s*=\\s*"
                    + "(\"\\s*(?:javascript|data|vbscript):[^\"]*\""
                    + "|'\\s*(?:javascript|data|vbscript):[^']*'"
                    + "|\\s*(?:javascript|data|vbscript):[^\\s>]+)");

    /**
     * 清洗邮件 HTML，保留正文基本结构并移除高风险内容。
     */
    @Override
    public String sanitizeHtml(String htmlBody) {
        if (htmlBody == null) {
            return null;
        }
        String sanitized = DANGEROUS_TAG_PATTERN.matcher(htmlBody).replaceAll("");
        sanitized = EVENT_ATTRIBUTE_PATTERN.matcher(sanitized).replaceAll("");
        sanitized = STYLE_ATTRIBUTE_PATTERN.matcher(sanitized).replaceAll("");
        return DANGEROUS_URL_ATTRIBUTE_PATTERN.matcher(sanitized).replaceAll("");
    }

    /**
     * 根据 HTML 是否存在返回前端渲染模式。
     */
    @Override
    public String htmlRenderMode(String htmlBody) {
        if (htmlBody == null || htmlBody.isBlank()) {
            return HTML_RENDER_MODE_TEXT_ONLY;
        }
        return HTML_RENDER_MODE_SANITIZED;
    }
}
