import { NextRequest, NextResponse } from "next/server";
import { getSkill, updateSkill, deleteSkill } from "@/lib/skills-registry";

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

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ skill: string }> }
) {
  const { skill: name } = await params;
  const body = (await request.json()) as {
    description?: string;
    version?: string;
    allowedTools?: string[];
    content?: string;
  };

  try {
    const skill = await updateSkill(name, body);
    return NextResponse.json({ skill });
  } 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<{ skill: string }> }
) {
  const { skill: name } = await params;
  const url = new URL(request.url);
  const deleteFile = url.searchParams.get("deleteFile") === "true";

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