import type { APIRoute } from "astro";

import { listPosts } from "../lib/api";

const SITE = "https://rubis.pro";

const STATIC_PAGES: Array<{ path: string; priority: string; changefreq: string }> = [
  { path: "/", priority: "1.0", changefreq: "weekly" },
  { path: "/blog", priority: "0.9", changefreq: "weekly" },
  { path: "/mentions-legales", priority: "0.3", changefreq: "yearly" },
  { path: "/confidentialite", priority: "0.3", changefreq: "yearly" },
  { path: "/cgv", priority: "0.3", changefreq: "yearly" },
];

/**
 * Sitemap unifié rubis.pro — pages statiques + tous les articles publiés
 * (hors noindex). Régénéré à chaque requête (cheap : O(N) sur la liste posts).
 */
export const GET: APIRoute = async () => {
  const posts = await listPosts();

  const staticUrls = STATIC_PAGES.map(
    ({ path, priority, changefreq }) =>
      `  <url>
    <loc>${SITE}${path}</loc>
    <changefreq>${changefreq}</changefreq>
    <priority>${priority}</priority>
  </url>`,
  ).join("\n");

  const postUrls = posts
    .map(
      (p) => `  <url>
    <loc>${SITE}/blog/${p.slug}</loc>${p.publishedAt ? `\n    <lastmod>${p.publishedAt}</lastmod>` : ""}
    <changefreq>monthly</changefreq>
    <priority>0.7</priority>
  </url>`,
    )
    .join("\n");

  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${staticUrls}
${postUrls}
</urlset>`;

  return new Response(xml, {
    status: 200,
    headers: {
      "Content-Type": "application/xml; charset=utf-8",
      "Cache-Control": "public, max-age=300, stale-while-revalidate=86400",
    },
  });
};
