import { NextResponse } from "next/server";
import { getType, updateType, deleteType } from "@/lib/tools-menu-registry";

export async function GET(_request: Request, { params }: { params: Promise<{ typeId: string }> }) {
  try {
    const { typeId } = await params;
    const toolType = await getType(typeId);
    if (!toolType) {
      return NextResponse.json({ error: "Tool type not found" }, { status: 404 });
    }
    return NextResponse.json({ type: toolType });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Unknown error" }, { status: 500 });
  }
}

export async function PUT(request: Request, { params }: { params: Promise<{ typeId: string }> }) {
  try {
    const { typeId } = await params;
    const updates = await request.json();
    const toolType = await updateType(typeId, updates);
    return NextResponse.json({ type: toolType });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Unknown error" }, { status: 500 });
  }
}

export async function DELETE(request: Request, { params }: { params: Promise<{ typeId: string }> }) {
  try {
    const { typeId } = await params;
    const url = new URL(request.url);
    const cascade = url.searchParams.get("cascade") === "true";
    const result = await deleteType(typeId, cascade);
    if (!result.deleted) {
      return NextResponse.json({ conflict: true, affectedTools: result.affectedTools }, { status: 409 });
    }
    return NextResponse.json({ ok: true });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Unknown error" }, { status: 500 });
  }
}
