import type { Locale } from "next-intl";
import { categorySlug } from "@/config/blog/categories";
import { site } from "@/config/site";
import { getAllPosts, localePrefix } from "@/lib/blog";

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

/**
 * Build a well-formed RSS 2.0 feed for a single locale.
 *
 * Paths are explicit per locale (no next-intl prefix-omission):
 * - en  -> served at `/feed.xml`     (self link `${site.url}/feed.xml`)
 * - fr  -> served at `/fr/feed.xml`  (self link `${site.url}/fr/feed.xml`)
 *
 * The `prefix` mirrors the served path so self-link/items match discovery.
 */
function buildRssFeed(locale: Locale): string {
  const prefix = localePrefix(locale);
  const self = `${site.url}${prefix}/feed.xml`;
  const channelLink = `${site.url}${prefix}`;

  const items = getAllPosts(locale)
    .map((p) => {
      const link = `${site.url}${prefix}/${categorySlug(p.category, locale)}/${p.slug}`;
      return `    <item>
      <title>${esc(p.title)}</title>
      <link>${link}</link>
      <guid isPermaLink="true">${link}</guid>
      <pubDate>${new Date(p.date).toUTCString()}</pubDate>
      <description>${esc(p.description)}</description>
    </item>`;
    })
    .join("\n");

  return `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>${esc(site.name)} Blog</title>
    <link>${channelLink}</link>
    <atom:link href="${self}" rel="self" type="application/rss+xml" />
    <description>${esc(site.description)}</description>
    <language>${locale}</language>
${items}
  </channel>
</rss>`;
}

export function rssResponse(locale: Locale): Response {
  return new Response(buildRssFeed(locale), {
    headers: { "Content-Type": "application/rss+xml; charset=utf-8" },
  });
}
