package com.pandoli365.bibimbap.service;

import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
import org.springframework.stereotype.Component;

@Component
public class PostMarkdownService {

    // Parser/HtmlRenderer are thread-safe and immutable once built.
    private final Parser parser = Parser.builder().build();
    private final HtmlRenderer renderer = HtmlRenderer.builder().build();

    public String render(String markdown) {
        if (markdown == null || markdown.isBlank()) {
            return "";
        }
        String rawHtml = renderer.render(parser.parse(markdown));
        // Empty baseUri so relative URLs are not resolved against a host.
        return Jsoup.clean(rawHtml, "", buildSafelist());
    }

    private Safelist buildSafelist() {
        return Safelist.basicWithImages()
                .addTags("h1", "h2", "h3", "hr")
                .addProtocols("a", "href", "http", "https", "mailto")
                .addEnforcedAttribute("a", "rel", "nofollow noopener")
                .addEnforcedAttribute("a", "target", "_blank")
                .addProtocols("img", "src", "http", "https");
    }
}
