import { NextResponse } from "next/server";
import { listTypes, addType, readToolsRegistry } from "@/lib/tools-menu-registry";

export async function GET(request: Request) {
  try {
    const url = new URL(request.url);
    const includeFields = url.searchParams.get("includeFields") === "true";
    const types = await listTypes();
    if (includeFields) {
      const registry = await readToolsRegistry();
      const typesWithFields = types.map(t => ({
        ...t,
        configFields: registry.typeDefinitions[t.id]?.configFields || [],
      }));
      return NextResponse.json({ types: typesWithFields });
    }
    return NextResponse.json({ types });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Unknown error" }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { name, description, icon, configFields } = body;
    if (!name) {
      return NextResponse.json({ error: "name is required" }, { status: 400 });
    }
    const toolType = await addType({ name, description, icon, configFields });
    return NextResponse.json({ type: toolType }, { status: 201 });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Unknown error" }, { status: 500 });
  }
}
