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

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

export async function GET(context: AstroUserConfig) {
  const { tag: selectedTag } = context.params;
  const posts = await getPublishedPosts(selectedTag);

  return rss({
    title: `${SITE_TITLE} - ${selectedTag}`,
    description: SITE_DESCRIPTION,
    site: context.site as string,
    items: posts.map((post) => ({
      ...post.data,
      link: `/blog/${post.id}/`,
    })),
  });
}

export async function getStaticPaths() {
  const posts = await getCollection("blog", publishedOnly);

  const tags = posts.flatMap((p) => p.data.tags);

  return tags.map((tag) => ({
    params: { tag: tag },
    props: { tag: tag },
  }));
}
