import rss from "@astrojs/rss";
import type { APIRoute } from "astro";
import { getCollection } from "astro:content";
import { blogFeedItem, type EntryWithPubDate } from "@utils/feed";

const MAX_ITEMS = 8;

export const GET: APIRoute = async ({ site }) => {
  if (!site) {
    throw new Error("site is required.");
  }
  const posts = (
    (await getCollection("blog", (post) => !post.data.isDraft && post.data.pubDate)) as EntryWithPubDate<"blog">[]
  )
    .sort((a, b) => b.data.pubDate.getTime() - a.data.pubDate.getTime())
    .slice(0, MAX_ITEMS);

  return rss({
    title: "Blog | Bad Manners",
    description: "Blog posts by Bad Manners.",
    site: new URL("blog", site),
    xmlns: { atom: "http://www.w3.org/2005/Atom" },
    customData: `<link href="${new URL("blog", site)}" rel="alternate" type="text/html" /><atom:link href="${new URL("blog/feed.xml", site)}" rel="self" type="application/rss+xml" />`,
    items: await Promise.all(
      posts.map(async ({ data, slug, render }) => blogFeedItem(site, data, slug, (await render()).Content)),
    ),
  });
};
