import { getCollection } from "astro:content";
import { join } from "node:path";
import type { APIContext, ImageMetadata } from "astro";
import { buildNoteVNode, imageToOgDataUri, renderOgImage } from "@/lib/og";

export async function getStaticPaths() {
  const notes = await getCollection("notes", ({ data }) => !data.draft);

  const imageModules = import.meta.glob<{ default: ImageMetadata }>(
    "/src/content/notes/**/*.{jpg,jpeg,png,webp}",
    { eager: true },
  );

  return notes.map((note) => {
    let coverPath: string | null = null;
    if (note.data.cover) {
      const entry = Object.entries(imageModules).find(
        ([, mod]) => mod.default.src === note.data.cover?.src,
      );
      coverPath = entry?.[0] ?? null;
    }
    return { params: { slug: note.id }, props: { coverPath } };
  });
}

export async function GET({ props }: APIContext) {
  const coverDataUri = props.coverPath
    ? await imageToOgDataUri(join(process.cwd(), props.coverPath))
    : undefined;
  const buffer = await renderOgImage(buildNoteVNode({ coverDataUri }));
  return new Response(buffer, { headers: { "Content-Type": "image/png" } });
}
