import { NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import { renderDesignSystemShowcase } from "@/lib/scaffold/open-design/design-system-showcase";

export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;

  if (!id || id.includes("..") || id.includes("/")) {
    return new NextResponse("Invalid design system ID", { status: 400 });
  }

  const systemPath = path.join(
    process.cwd(),
    "lib",
    "scaffold",
    "open-design",
    "design-systems",
    id
  );

  const mdPath = path.join(systemPath, "DESIGN.md");

  try {
    if (!fs.existsSync(systemPath)) {
      return new NextResponse(`Design system not found for ${id}`, { status: 404 });
    }

    if (!fs.existsSync(mdPath)) {
      return new NextResponse(`DESIGN.md not found for ${id}`, { status: 404 });
    }

    const rawMarkdown = await fs.promises.readFile(mdPath, "utf-8");
    const html = renderDesignSystemShowcase(id, rawMarkdown);

    return new NextResponse(html, {
      status: 200,
      headers: {
        "Content-Type": "text/html; charset=utf-8",
        "X-Frame-Options": "SAMEORIGIN",
      },
    });
  } catch (err: any) {
    return new NextResponse(`Error loading showcase: ${err.message}`, {
      status: 500,
    });
  }
}
