import type { APIRoute } from 'astro';
import { getCollection, type CollectionEntry } from 'astro:content';

export const GET: APIRoute = async ({ site }) => {
  const updates = await getCollection('updates');
  const sorted = updates.sort(
    (a: CollectionEntry<'updates'>, b: CollectionEntry<'updates'>) =>
      new Date(b.data.date).getTime() - new Date(a.data.date).getTime()
  );

  const base = 'https://bifrost.fenja.ai';

  const items = sorted.map((u: CollectionEntry<'updates'>) => {
    const url = `${base}/updates/${u.slug}`;
    const date = new Date(u.data.date).toUTCString();
    return `
    <item>
      <title><![CDATA[${u.data.title}]]></title>
      <description><![CDATA[${u.data.summary}]]></description>
      <link>${url}</link>
      <guid isPermaLink="true">${url}</guid>
      <pubDate>${date}</pubDate>
      <author>${u.data.author}</author>
    </item>`;
  });

  const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Project Bifrost — Updates</title>
    <description>Progress notes from Fenja AI during the Bifrost pilot.</description>
    <link>${base}/updates</link>
    <atom:link href="${base}/updates/feed.xml" rel="self" type="application/rss+xml"/>
    <language>en</language>
    ${items.join('')}
  </channel>
</rss>`;

  return new Response(xml, {
    headers: { 'Content-Type': 'application/rss+xml; charset=utf-8' },
  });
};
