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

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

  const index = posts.map((post) => {
    const slug = post.id.replace(/^cs\//, '').replace(/\.md$/, '');
    return {
      slug,
      title: post.data.title,
      description: post.data.description,
      image: post.data.image,
      date: post.data.date.toISOString().split('T')[0],
      body: post.body,
    };
  });

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