import type { APIRoute } from 'astro';
import { site } from '../config/site';
import { getPosts } from '../lib/posts';

const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');

/** RSS 2.0 feed of published blog posts (/rss.xml). */
export const GET: APIRoute = async () => {
  const posts = await getPosts();
  const items = posts.map((p) => `    <item>
      <title>${esc(p.title)}</title>
      <link>${site.url}/blog/${p.slug}/</link>
      <guid isPermaLink="true">${site.url}/blog/${p.slug}/</guid>
      <pubDate>${new Date(p.published_at || Date.now()).toUTCString()}</pubDate>
      ${p.category ? `<category>${esc(p.category)}</category>` : ''}
      <description>${esc(p.excerpt || '')}</description>
    </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>${esc(site.name)} Blog</title>
    <link>${site.url}/blog/</link>
    <atom:link href="${site.url}/rss.xml" rel="self" type="application/rss+xml" />
    <description>Guides for small trucking companies: trip sheets, IFTA mileage, driver pay and fleet management.</description>
    <language>en-us</language>
${items}
  </channel>
</rss>
`;
  return new Response(xml, { headers: { 'Content-Type': 'application/rss+xml; charset=utf-8' } });
};
