import { NextResponse } from "next/server";
import { getApp, updateApp, deleteApp } from "@/lib/apps-registry";

export async function GET(_request: Request, { params }: { params: Promise<{ appId: string }> }) {
  try {
    const { appId } = await params;
    const app = await getApp(appId);
    if (!app) {
      return NextResponse.json({ error: "App not found" }, { status: 404 });
    }
    return NextResponse.json({ app });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Unknown error" }, { status: 500 });
  }
}

export async function PUT(request: Request, { params }: { params: Promise<{ appId: string }> }) {
  try {
    const { appId } = await params;
    const updates = await request.json();
    const app = await updateApp(appId, updates);
    return NextResponse.json({ app });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Unknown error" }, { status: 500 });
  }
}

export async function DELETE(_request: Request, { params }: { params: Promise<{ appId: string }> }) {
  try {
    const { appId } = await params;
    await deleteApp(appId);
    return NextResponse.json({ ok: true });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Unknown error" }, { status: 500 });
  }
}
