import type { RequestHandler } from './$types';
import { getCategoriesWithCounts, getIndexableCalculators } from '$lib/data/calculators';
import { canonicalUrl, escapeXml } from '$lib/seo';

export const GET: RequestHandler = async () => {
	const calculatorUrls = getIndexableCalculators().map(
		(calc) => `  <url>
    <loc>${escapeXml(canonicalUrl(`/${calc.slug}`))}</loc>
    <changefreq>monthly</changefreq>
    <priority>0.8</priority>
  </url>`
	);

	const categoryUrls = getCategoriesWithCounts().filter(category => category.count > 0).map(
		(category) => `  <url>
    <loc>${escapeXml(canonicalUrl(`/category/${category.key}`))}</loc>
    <changefreq>weekly</changefreq>
    <priority>0.9</priority>
  </url>`
	);

	const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>${escapeXml(canonicalUrl('/'))}</loc>
    <changefreq>weekly</changefreq>
    <priority>1.0</priority>
  </url>
${categoryUrls.join('\n')}
${calculatorUrls.join('\n')}
</urlset>`;

	return new Response(sitemap, {
		headers: {
			'Content-Type': 'application/xml',
			'Cache-Control': 'max-age=0, s-maxage=3600'
		}
	});
};
