import type { APIRoute } from 'astro';
import { PAGE_IDS, pathFor } from '@i18n/slugMap';
import { LOCALES } from '@i18n/locales';
import { absUrl, alternates } from '@lib/seo';

/*
  Sitemap built from the slug map (ARCHITECTURE A5, SEO_SPEC §5). Every URL carries
  xhtml:link alternates for both locales + x-default, mirroring the hreflang tags.
*/
export const GET: APIRoute = ({ site }) => {
  const origin = site?.href ?? 'https://cesnimda.co.uk/';

  const urls: string[] = [];
  for (const pageId of PAGE_IDS) {
    const alts = alternates(pageId, origin);
    const altXml = alts
      .map((a) => `    <xhtml:link rel="alternate" hreflang="${a.hreflang}" href="${a.href}" />`)
      .join('\n');
    for (const locale of LOCALES) {
      urls.push(
        `  <url>\n    <loc>${absUrl(pathFor(pageId, locale), origin)}</loc>\n${altXml}\n  </url>`,
      );
    }
  }

  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
${urls.join('\n')}
</urlset>
`;

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