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

export async function getStaticPaths() {
  const all = await getCollection('posts');
  const slugs = new Map<string, string>();
  for (const p of all) {
    p.data.categorySlugs.forEach((s, i) => {
      if (!slugs.has(s)) slugs.set(s, p.data.categories[i] ?? s);
    });
  }
  return [...slugs.entries()].map(([slug, name]) => ({
    params: { slug },
    props: { catSlug: slug, catName: name },
  }));
}

export const GET = async ({ props }: { props: { catSlug: string; catName: string } }) => {
  const { catSlug, catName } = props;
  const all = await getCollection('posts');
  const items = all
    .filter((p) => p.data.categorySlugs.includes(catSlug) && 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: [catName],
      };
    });

  const xml = buildRss({
    title: `${SITE_TITLE} — ${catName}`,
    description: `Рубрика «${catName}»`,
    selfUrl: `${SITE_URL}/cat/${catSlug}/feed.xml`,
    language: SITE_LANG,
    items,
  });

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