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 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 items = 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}/`,
      }));
    })
    .sort((a, b) => b.pubDate.valueOf() - a.pubDate.valueOf());

  return rss({
    title: "Adrian Altner — Photos",
    description: "Photography from travels and photowalks.",
    site: context.site ?? new URL("https://adrian-altner.com"),
    items,
    customData: "<language>en-us</language>",
  });
}
