import { getCollection } from 'astro:content';
import type { APIRoute } from 'astro';

export const GET: APIRoute = async () => {
  const allPosts = await getCollection('blog', ({ data }) => !data.draft);
  const csPosts = allPosts
    .filter(p => p.id.startsWith('cs/'))
    .sort((a, b) => b.data.date.valueOf() - a.data.date.valueOf());
  const enPosts = allPosts.filter(p => p.id.startsWith('en/'));

  // For each CS article, use EN version if available, otherwise fall back to CS
  const index = csPosts.map((csPost) => {
    const baseSlug = csPost.id.replace(/^cs\//, '').replace(/\.md$/, '');
    const enPost = enPosts.find(p => p.id.replace(/^en\//, '').replace(/\.md$/, '') === baseSlug);
    const post = enPost ?? csPost;
    return {
      slug: baseSlug,
      title: post.data.title,
      description: post.data.description,
      image: post.data.image,
      date: post.data.date.toISOString().split('T')[0],
      body: post.body,
      lang: enPost ? 'en' : 'cs',
    };
  });

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