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

export const GET: APIRoute = async () => {
  try {
    const posts = await getCollection("posts");

    const postsWithContent = posts.map((post) => ({
      slug: post.id,
      title: post.data.title,
      description: post.data.description,
      pubDate: post.data.pubDate.toISOString().split("T")[0],
      tags: post.data.tags || [],
      content: post.body,
    }));

    return new Response(JSON.stringify(postsWithContent), {
      status: 200,
      headers: {
        "Content-Type": "application/json",
      },
    });
  } catch (error) {
    console.error("Error fetching posts:", error);
    return new Response(JSON.stringify([]), {
      status: 500,
      headers: {
        "Content-Type": "application/json",
      },
    });
  }
};
