import { NextRequest, NextResponse } from "next/server";
import { listSkills, addSkill, addSkillFromPath } from "@/lib/skills-registry";

export async function GET() {
  const skills = await listSkills();
  return NextResponse.json({ skills });
}

export async function POST(request: NextRequest) {
  const contentType = request.headers.get("content-type") || "";

  try {
    if (contentType.includes("multipart/form-data")) {
      const formData = await request.formData();
      const file = formData.get("file") as File | null;
      if (!file) {
        return NextResponse.json({ error: "No file provided" }, { status: 400 });
      }
      const content = await file.text();
      const skill = await addSkill(content, file.name);
      return NextResponse.json({ skill }, { status: 201 });
    }

    const body = (await request.json()) as { path?: string };
    if (!body.path) {
      return NextResponse.json({ error: "Missing path" }, { status: 400 });
    }
    const skill = await addSkillFromPath(body.path);
    return NextResponse.json({ skill }, { status: 201 });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json({ error: message }, { status: 400 });
  }
}
