import { NextResponse } from "next/server";
import { listApps, addApp } from "@/lib/apps-registry";

export async function GET(request: Request) {
  try {
    const url = new URL(request.url);
    const hostId = url.searchParams.get("hostId") || undefined;
    const categoryId = url.searchParams.get("categoryId") || undefined;
    const apps = await listApps({ hostId, categoryId });
    return NextResponse.json({ apps });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Unknown error" }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { name, url: appUrl, hostId, categoryId, description, icon, color } = body;
    if (!name || !appUrl || !hostId || !categoryId) {
      return NextResponse.json({ error: "name, url, hostId, and categoryId are required" }, { status: 400 });
    }
    const app = await addApp({ name, url: appUrl, hostId, categoryId, description, icon, color });
    return NextResponse.json({ app }, { status: 201 });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Unknown error" }, { status: 500 });
  }
}
