import { NextRequest, NextResponse } from "next/server";
import { getMcpServer, updateMcpServer, deleteMcpServer } from "@/lib/skills-registry";

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ server: string }> }
) {
  const { server: name } = await params;
  const server = await getMcpServer(name);
  if (!server) {
    return NextResponse.json({ error: "MCP server not found" }, { status: 404 });
  }
  return NextResponse.json({ server });
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ server: string }> }
) {
  const { server: name } = await params;
  const body = (await request.json()) as {
    description?: string;
    command?: string;
    args?: string[];
    env?: Record<string, string>;
  };

  try {
    const server = await updateMcpServer(name, body);
    return NextResponse.json({ server });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json({ error: message }, { status: 404 });
  }
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: Promise<{ server: string }> }
) {
  const { server: name } = await params;

  try {
    const affectedAgents = await deleteMcpServer(name);
    return NextResponse.json({ ok: true, syncedAgents: affectedAgents });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json({ error: message }, { status: 404 });
  }
}
