import rss from "@astrojs/rss";
import { SITE_TITLE, SITE_DESCRIPTION } from "../consts";
import { getCollection, type CollectionEntry } from "astro:content";
import type { AstroUserConfig } from "astro";

function publishedOnly(
  p: CollectionEntry<"blog">,
): p is CollectionEntry<"blog"> & { data: { pubDate: Date } } {
  return p.data.pubDate !== undefined;
}

export async function GET(context: AstroUserConfig) {
  const posts = (await getCollection("blog", publishedOnly)).sort(
    (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
  );
  return rss({
    title: SITE_TITLE,
    description: SITE_DESCRIPTION,
    site: context.site as string,
    items: posts.map((post) => ({
      ...post.data,
      link: `/blog/${post.id}/`,
    })),
  });
}
