import { getCollection } from "astro:content";
import rss from "@astrojs/rss";
import type { APIContext, ImageMetadata } from "astro";
import type { PhotoSidecar } from "@/lib/collections";
import { buildCollectionPhotos, collectionSlug } from "@/lib/collections";

export async function GET(context: APIContext) {
  const articles = await getCollection("blog", ({ data }) => !data.draft);
  const notes = await getCollection("notes", ({ data }) => !data.draft);
  const links = await getCollection("links_json");
  const allCollections = await getCollection(
    "collections_photos",
    ({ data }) => !data.draft,
  );

  const sidecars = import.meta.glob<PhotoSidecar>(
    "/src/content/photos/collections/**/*.json",
    { eager: true },
  );
  const imageModules = import.meta.glob<{ default: ImageMetadata }>(
    "/src/content/photos/collections/**/*.jpg",
    { eager: true },
  );

  const articleItems = articles.map((post) => ({
    title: post.data.title,
    description: post.data.description,
    pubDate: post.data.publishDate,
    link: `/blog/${post.id}/`,
  }));

  const noteItems = notes.map((note) => ({
    title: note.data.title,
    description: note.data.description ?? note.data.title,
    pubDate: note.data.publishDate,
    link: `/notes/${note.id}/`,
  }));

  const linkItems = links.map((link) => ({
    title: link.data.title,
    description: link.data.description ?? link.data.title,
    pubDate: link.data.publishDate,
    link: `/links/${link.id}/`,
  }));

  const photoItems = allCollections.flatMap((col) => {
    const slug = collectionSlug(col);
    return buildCollectionPhotos(sidecars, imageModules, slug).map((p) => ({
      title: p.sidecar.title[0] ?? p.sidecar.id,
      description: p.sidecar.alt,
      pubDate: new Date(p.sidecar.date),
      link: `/photos/collections/${slug}/${p.sidecar.id}/`,
    }));
  });

  const items = [
    ...articleItems,
    ...noteItems,
    ...linkItems,
    ...photoItems,
  ].sort((a, b) => b.pubDate.valueOf() - a.pubDate.valueOf());

  return rss({
    title: "Adrian Altner",
    description:
      "Passionate photographer and avid traveler, bridging a deep technological curiosity with a keen eye for the latest digital innovations.",
    site: context.site ?? new URL("https://adrian-altner.com"),
    items,
    customData: "<language>en-us</language>",
  });
}
