import { getCollection } from "astro:content";

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 items = posts
    .sort((a, b) => b.data.date.localeCompare(a.data.date))
    .map((post) => `<item><title>${escapeXml(post.data.title)}</title><link>${escapeXml(post.data.canonicalUrl)}</link><guid>${escapeXml(post.data.canonicalUrl)}</guid><pubDate>${new Date(`${post.data.date}T00:00:00+08:00`).toUTCString()}</pubDate><description>${escapeXml(post.data.summary)}</description></item>`)
    .join("");
  const xml = `<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><title>K1412 Research</title><link>https://blog.k1412.top</link><description>技术研究、实验记录与可验证的公开成果。</description>${items}</channel></rss>`;
  return new Response(xml, { headers: { "Content-Type": "application/rss+xml; charset=utf-8" } });
}
