import { allBlogPosts } from "content-collections";

const BASE_URL = "https://www.elevaseo.com";
const MAX_ITEMS = 50;
const WEBSUB_HUB = "https://pubsubhubbub.appspot.com/";

export function generateRssFeed(locale: string): Response {
  const posts = allBlogPosts
    .filter((post) => post.locale === locale && post.published)
    .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
    .slice(0, MAX_ITEMS);

  const prefix = locale === "fr" ? "" : `/${locale}`;
  const feedTitle =
    locale === "fr" ? "ElevaSEO Blog" : "ElevaSEO Blog (English)";
  const feedDescription =
    locale === "fr"
      ? "Articles sur le SEO technique, la performance web, le headless CMS et WordPress."
      : "Articles about technical SEO, web performance, headless CMS and WordPress.";
  const feedUrl = `${BASE_URL}${prefix}/blog/rss.xml`;
  const blogUrl = `${BASE_URL}${prefix}/blog`;

  const items = posts
    .map((post) => {
      const url = `${BASE_URL}${prefix}/blog/${post.categorySlug}/${post.slug}`;
      const pubDate = new Date(post.lastmod || post.date).toUTCString();
      return `    <item>
      <title><![CDATA[${post.title}]]></title>
      <link>${url}</link>
      <guid isPermaLink="true">${url}</guid>
      <description><![CDATA[${post.description}]]></description>
      <pubDate>${pubDate}</pubDate>
      <author>bastien@elevaseo.com (Bastien Allain)</author>
      <category>${post.category}</category>
    </item>`;
    })
    .join("\n");

  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>${feedTitle}</title>
    <link>${blogUrl}</link>
    <description>${feedDescription}</description>
    <language>${locale}</language>
    <lastBuildDate>${new Date().toUTCString()}</lastBuildDate>
    <atom:link href="${feedUrl}" rel="self" type="application/rss+xml" />
    <atom:link href="${WEBSUB_HUB}" rel="hub" />
${items}
  </channel>
</rss>`;

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