import { NextRequest, NextResponse } from "next/server";
import { updateSkillAgents, reloadAgentSkills } from "@/lib/skills-registry";

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

  if (!Array.isArray(body.agents)) {
    return NextResponse.json({ error: "agents must be an array" }, { status: 400 });
  }

  try {
    const { skill, previousAgents } = await updateSkillAgents(name, body.agents);

    // Reload skills on all affected agents — both added and removed (fire-and-forget)
    const allAffected = new Set([...skill.agents, ...previousAgents]);
    for (const agent of allAffected) {
      reloadAgentSkills(agent).catch(() => {});
    }

    return NextResponse.json({ skill });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json({ error: message }, { status: 404 });
  }
}
