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

export async function GET(_request: Request, { params }: { params: Promise<{ viewKey: string }> }) {
  try {
    const { viewKey } = await params;
    const order = await getViewOrder(decodeURIComponent(viewKey));
    return NextResponse.json({ order });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Unknown error" }, { status: 500 });
  }
}

export async function PUT(request: Request, { params }: { params: Promise<{ viewKey: string }> }) {
  try {
    const { viewKey } = await params;
    const { order } = await request.json();
    if (!Array.isArray(order)) {
      return NextResponse.json({ error: "order must be an array of app IDs" }, { status: 400 });
    }
    await updateViewOrder(decodeURIComponent(viewKey), order);
    return NextResponse.json({ ok: true });
  } catch (err) {
    return NextResponse.json({ error: err instanceof Error ? err.message : "Unknown error" }, { status: 500 });
  }
}
