const sanitizeHtml = require("sanitize-html");

const SANITIZE_OPTIONS = {
	allowedTags: [
		"p",
		"br",
		"div",
		"span",
		"strong",
		"b",
		"em",
		"i",
		"u",
		"s",
		"del",
		"strike",
		"h1",
		"h2",
		"h3",
		"h4",
		"h5",
		"h6",
		"ul",
		"ol",
		"li",
		"blockquote",
		"pre",
		"code",
		"hr",
		"a",
		"table",
		"thead",
		"tbody",
		"tfoot",
		"tr",
		"th",
		"td",
	],
	allowedAttributes: {
		a: ["href", "target", "rel", "name"],
		th: ["colspan", "rowspan", "align"],
		td: ["colspan", "rowspan", "align"],
	},
	allowedSchemes: ["http", "https", "mailto", "tel"],
	transformTags: {
		a: (tagName, attribs) => {
			const next = { ...attribs };
			if (next.target === "_blank") {
				next.rel = (next.rel || "noopener") + (next.rel && next.rel.indexOf("noreferrer") >= 0 ? "" : " noreferrer");
			}
			return { tagName, attribs: next };
		},
	},
};

/**
 * @param {string} html
 * @returns {string}
 */
function sanitizeUseCaseBody(html) {
	if (html == null) return "";
	return sanitizeHtml(String(html), SANITIZE_OPTIONS);
}

module.exports = { sanitizeUseCaseBody };
