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

const MAX_ITEMS = 8;

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

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