import rss from "@astrojs/rss";
import type { APIRoute } from "astro";
import { getCollection } from "astro:content";
import { gameFeedItem, 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("games", (game) => !game.data.isDraft && game.data.pubDate)) as EntryWithPubDate<"games">[]
  )
    .sort((a, b) => b.data.pubDate.getTime() - a.data.pubDate.getTime())
    .slice(0, MAX_ITEMS);

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