import type { TourDraft } from "@circuy/contracts";
import sanitizeHtml from "sanitize-html";

const allowedTags = [
	"em",
	"strong",
	"b",
	"i",
	"a",
	"ul",
	"ol",
	"li",
	"br",
	"p",
];

export function sanitizeBodyHtml(html: string): string {
	return sanitizeHtml(html, {
		allowedTags,
		allowedAttributes: { a: ["href", "rel"] },
		allowedSchemes: ["http", "https", "mailto"],
		allowProtocolRelative: false,
		transformTags: {
			a: (_tagName, attribs) => {
				const next: Record<string, string> = { rel: "noopener noreferrer" };
				if (attribs.href) next.href = attribs.href;
				return { tagName: "a", attribs: next };
			},
		},
	});
}

export function sanitizeDraft(draft: TourDraft): TourDraft {
	return {
		...draft,
		steps: draft.steps.map((step) =>
			"body" in step ? { ...step, body: sanitizeBodyHtml(step.body) } : step,
		),
	};
}
