import { getCollection } from "astro:content";

const localPages = ["/", "/archive/", "/method/"];

function escapeXml(value: string) {
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
}

export async function GET() {
  const posts = await getCollection("posts", ({ data }) => data.status === "published");
  const urls = [
    ...localPages.map((path) => ({ loc: new URL(path, "https://blog.k1412.top").href, lastmod: "2026-08-10" })),
    ...posts.map((post) => ({ loc: post.data.canonicalUrl, lastmod: post.data.updated }))
  ];
  const entries = urls.map(({ loc, lastmod }) => `<url><loc>${escapeXml(loc)}</loc><lastmod>${escapeXml(lastmod)}</lastmod></url>`).join("");
  const xml = `<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${entries}</urlset>`;
  return new Response(xml, { headers: { "Content-Type": "application/xml; charset=utf-8" } });
}
