import { getCollection } from 'astro:content';

export async function GET() {
  const [reviews, finds, lists, posts] = await Promise.all([
    getCollection('reviews'),
    getCollection('find'),
    getCollection('finds'),
    getCollection('posts'),
  ]);

  const entries = [
    ...reviews.map((r) => ({
      type: 'review',
      url: `/reviews/${r.id}/`,
      title: r.data.name,
      subtitle: r.data.subtitle ?? '',
      date: r.data.date.toISOString(),
      tags: r.data.tags ?? [],
      blurb: r.data.description ?? '',
    })),
    ...finds.map((f) => ({
      type: 'find',
      url: `/find/${f.id}/`,
      title: f.data.name,
      subtitle: f.data.subtitle ?? '',
      date: f.data.date.toISOString(),
      tags: f.data.tags ?? [],
      blurb: f.data.description ?? '',
      source: f.data.source,
    })),
    ...lists.map((l) => ({
      type: 'list',
      url: `/finds/${l.id}/`,
      title: l.data.title,
      subtitle: l.data.blurb ?? '',
      date: l.data.date.toISOString(),
      tags: l.data.tags ?? [],
      blurb: l.data.description ?? '',
    })),
    ...posts.map((p) => ({
      type: 'post',
      url: `/posts/${p.id}/`,
      title: p.data.title,
      subtitle: '',
      date: p.data.date.toISOString(),
      tags: p.data.tags ?? [],
      blurb: p.data.description ?? '',
    })),
  ];

  entries.sort((a, b) => b.date.localeCompare(a.date));

  return new Response(JSON.stringify({ entries }), {
    headers: { 'Content-Type': 'application/json' },
  });
}
