import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export const runtime = "nodejs"; // Force Node runtime

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const slug = searchParams.get("slug");

  if (!slug) {
    return NextResponse.json({ error: "Slug is required" }, { status: 400 });
  }

  try {
    const project = await prisma.project.findUnique({
      where: { slug },
      select: {
        id: true,
        slug: true,
        title: true,
        updatedAt: true,
        metaDescription: true,
        description: true,
        content: true,
      },
    });

    if (!project) {
      return NextResponse.json({ posts: [] }, { status: 200 });
    }

    // Legacy shape (Ghost-like) for compatibility with older frontend/tests.
    return NextResponse.json({
      posts: [
        {
          id: String(project.id),
          title: project.title,
          meta_description: project.metaDescription ?? project.description ?? "",
          slug: project.slug,
          updated_at: (project.updatedAt ?? new Date()).toISOString(),
        },
      ],
    });
  } catch (error) {
    console.error("Failed to fetch project:", error);
    return NextResponse.json(
      { error: "Failed to fetch project" },
      { status: 500 },
    );
  }
}
