import type { RequestHandler } from './$types';
import { getAllPosts } from '$lib/blog/posts';
import { blogName, blogTagline } from '$lib/config/blog';
import { formatRssDate } from '$lib/blog/date';

function escapeXml(text: string): string {
	return text
		.replace(/&/g, '&amp;')
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;')
		.replace(/"/g, '&quot;')
		.replace(/'/g, '&apos;');
}

export const GET: RequestHandler = ({ url }) => {
	const items = getAllPosts()
		.map((post) => {
			const link = `${url.origin}/blog/${post.slug}`;
			const pubDate = formatRssDate(post.date);
			return `
		<item>
			<title>${escapeXml(post.title)}</title>
			<link>${link}</link>
			<guid>${link}</guid>
			<pubDate>${pubDate}</pubDate>
			<author>${escapeXml(post.author)}</author>
			<description>${escapeXml(post.excerpt)}</description>
		</item>`;
		})
		.join('');

	const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title>${escapeXml(blogName)}</title>
		<link>${url.origin}/blog</link>
		<description>${escapeXml(blogTagline)}</description>${items}
	</channel>
</rss>`;

	return new Response(xml, {
		headers: { 'Content-Type': 'application/xml' }
	});
};
