import { mongoConnect } from '$lib/database/mongo.server';
import { marked } from 'marked';
import * as path from 'path';
import sanitizeHtml from 'sanitize-html';

import type { Article } from '$lib/posts/types';
import type { _Renderer } from 'Renderer';

export async function load({ params }) {
	const slug = params.slug;
	const db = await mongoConnect();
	const query = {
		slug: slug
	};
	const col = db.db('fredboniface').collection('posts');
	const res = await col.findOne(query);

	if (!res) {
		throw new Error('Post Not Found');
	}

	const renderer = new marked.Renderer();
	renderer.image = function (href, title, text) {
		const imgPath = path.join('/images/posts', res.slug, href);
		return `<figure>
		<img class="post-inline-image-546543" src="${imgPath}" alt="${text}" title="${title}">
		<figcaption>${title}</figcaption>
		</figure>`;
	};

	const post: Article = {
		title: res.title,
		author: res.author,
		pusblished: res.published,
		summary: res.summary,
		content: renderMarkdown(res.content, renderer),
		slug: res.slug,
		tags: res.tags,
		date: res.date
	};

	return { data: post };
}

function renderMarkdown(md: string, renderer: _Renderer): string {
	const rawHtml = marked(md, { renderer });
	const sanitizedHtml = sanitizeHtml(rawHtml, {
		allowedTags: ['a', 'br', 'code', 'figcaption', 'figure', 'img', 'p', 'pre'],
		allowedAttributes: {
			a: ['href'],
			img: ['alt', 'class', 'src', 'title']
		}
	});
	return sanitizedHtml;
}
