import { type NextRequest, NextResponse } from "next/server";
import { gatewayUrl } from "@/lib/api/gateway";
import { getAccessToken } from "@/lib/auth/session";
import { decodeJwt } from "@/lib/auth/jwt";

export const runtime = "nodejs";

/** Create a render node (POST body forwarded to the gateway). Admin-gated. */
export async function POST(req: NextRequest) {
  const token = await getAccessToken();
  if (!token) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const claims = decodeJwt(token);
  const isAdmin =
    String(claims?.is_admin) === "true" || claims?.is_admin === true || String(claims?.is_tenant_admin) === "true";
  if (!isAdmin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const body = await req.text();
  const res = await fetch(gatewayUrl("/v1/nodes"), {
    method: "POST",
    cache: "no-store",
    headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
    body,
  });
  const data = await res.json().catch(() => null);
  if (!res.ok) {
    return NextResponse.json(
      { error: data?.message ?? data?.error?.message ?? "Gateway error" },
      { status: res.status }
    );
  }
  return NextResponse.json(data ?? { ok: true });
}
