import { getLegacyArticlesBySection } from "@/lib/articles/legacy-source";

export const dynamic = "force-dynamic";
export const revalidate = 1800;

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || "https://avbeat.com";

function escapeXml(s: string): string {
  return s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&apos;");
}

export async function GET() {
  let items = "";
  try {
    const articles = await getLegacyArticlesBySection("news", 50);
    items = articles
      .filter((a) => !a.noindex)  // exclude passthrough PR submissions
      .map((a) => {
        const url = `${SITE_URL}/news/${a.slug}`;
        const pubDate = a.date ? new Date(a.date).toUTCString() : new Date().toUTCString();
        const title = escapeXml(a.title || "Untitled");
        const description = escapeXml(a.excerpt || "");
        return `    <item>
      <title>${title}</title>
      <link>${url}</link>
      <guid isPermaLink="true">${url}</guid>
      <pubDate>${pubDate}</pubDate>
      <description>${description}</description>
    </item>`;
      })
      .join("\n");
  } catch {
    // serve an empty but valid feed on failure
    items = "";
  }

  const body = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>AV Beat</title>
    <link>${SITE_URL}</link>
    <atom:link href="${SITE_URL}/rss" rel="self" type="application/rss+xml" />
    <description>Pro AV, Display and Live Production Tech</description>
    <language>en-us</language>
    <lastBuildDate>${new Date().toUTCString()}</lastBuildDate>
${items}
  </channel>
</rss>`;

  return new Response(body, {
    headers: {
      "Content-Type": "application/rss+xml; charset=utf-8",
      "Cache-Control": "public, max-age=1800, s-maxage=1800, stale-while-revalidate=3600",
    },
  });
}
