import type { APIRoute } from "astro";

import { listPosts } from "../../lib/api";

const SITE = "https://rubis.pro";

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

function toRfc2822(iso: string | null): string {
  if (!iso) return "";
  return new Date(iso).toUTCString();
}

/**
 * Flux RSS 2.0 — 20 derniers articles publiés. Auto-discovered depuis
 * Layout.astro via <link rel="alternate" type="application/rss+xml">.
 */
export const GET: APIRoute = async () => {
  const posts = (await listPosts()).slice(0, 20);
  const lastBuild = posts[0]?.publishedAt ? toRfc2822(posts[0].publishedAt) : new Date().toUTCString();

  const items = posts
    .map((p) => {
      const url = `${SITE}/blog/${p.slug}`;
      return `    <item>
      <title>${escapeXml(p.title)}</title>
      <link>${escapeXml(url)}</link>
      <guid isPermaLink="true">${escapeXml(url)}</guid>
      <pubDate>${toRfc2822(p.publishedAt)}</pubDate>
      <description>${escapeXml(p.excerpt)}</description>
      <author>contact@rubis.pro (${escapeXml(p.authorName)})</author>
    </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>Rubis sur l'ongle — Blog</title>
    <link>${SITE}/blog</link>
    <atom:link href="${SITE}/blog/rss.xml" rel="self" type="application/rss+xml" />
    <description>Stratégies, modèles d'email et retours du terrain pour relancer vos factures impayées sans abîmer la relation client.</description>
    <language>fr-FR</language>
    <lastBuildDate>${lastBuild}</lastBuildDate>
${items}
  </channel>
</rss>`;

  return new Response(xml, {
    status: 200,
    headers: {
      "Content-Type": "application/xml; charset=utf-8",
      "Cache-Control": "public, max-age=300, stale-while-revalidate=86400",
    },
  });
};
