import { getCollection } from 'astro:content';

const site = 'https://truetraceshorts.pages.dev';
const staticRoutes = ['/', '/already-clicked/', '/safety/', '/checklist/', '/redflags/', '/tools/', '/about/', '/privacy/', '/terms/'];

export async function GET() {
  const redflags = await getCollection('redflags');
  const routes = [
    ...staticRoutes.map((path) => ({ path, lastmod: new Date().toISOString().slice(0, 10), priority: path === '/' ? '1.0' : '0.7' })),
    ...redflags.map((entry) => ({
      path: `/redflags/${entry.data.slug}/`,
      lastmod: entry.data.lastUpdated.toISOString().slice(0, 10),
      priority: '0.8',
    })),
  ];

  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${routes.map((route) => `  <url>
    <loc>${new URL(route.path, site).toString()}</loc>
    <lastmod>${route.lastmod}</lastmod>
    <priority>${route.priority}</priority>
  </url>`).join('\n')}
</urlset>`;

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