import type { APIRoute } from 'astro';
import { getPublishedProducts } from '../lib/sanity.mjs';

export const GET: APIRoute = async () => {
  const products = await getPublishedProducts();
  const today = new Date().toISOString().split('T')[0];

  const productUrls = products
    .map(
      (p: any) =>
        `  <url>
    <loc>https://rebours.studio/collection/${p.slug}</loc>
    <lastmod>${today}</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.8</priority>
  </url>`
    )
    .join('\n');

  const body = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://rebours.studio/</loc>
    <lastmod>${today}</lastmod>
    <changefreq>weekly</changefreq>
    <priority>1.0</priority>
  </url>
${productUrls}
</urlset>`;

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