import { getCollection } from 'astro:content';
import {
  SITE_TITLE,
  SITE_DESCRIPTION,
  SITE_URL,
  SITE_LANG,
  RSS_CUTOFF,
  RSS_LIMIT,
} from '../consts';
import { buildRss, plainTextExcerpt, sanitizeForRss } from '../lib/rss-helpers';

export const GET = async () => {
  const all = await getCollection('posts');
  const items = all
    .filter((p) => p.data.pubDate >= RSS_CUTOFF)
    .sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf())
    .slice(0, RSS_LIMIT)
    .map((p) => {
      const link = `${SITE_URL}/${p.data.slug}/`;
      const contentHtml = sanitizeForRss(p.body ?? '');
      const description = p.data.description || plainTextExcerpt(contentHtml, 500);
      return {
        title: p.data.title,
        link,
        pubDate: p.data.pubDate,
        description,
        contentHtml,
        author: p.data.author,
        categories: p.data.categories,
      };
    });

  const xml = buildRss({
    title: SITE_TITLE,
    description: SITE_DESCRIPTION,
    selfUrl: `${SITE_URL}/feed.xml`,
    language: SITE_LANG,
    items,
  });

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