// "Drain" sets node status to Draining via PATCH so it finishes its current
// job but won't accept new ones.
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";
interface Ctx { params: { nodeId: string } }

export async function POST(_req: NextRequest, { params }: Ctx) {
  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;
  if (!isAdmin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const res = await fetch(gatewayUrl(`/v1/nodes/${params.nodeId}`), {
    method: "PATCH",
    cache: "no-store",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ status: "Draining" }),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => null) as { message?: string } | null;
    return NextResponse.json({ error: err?.message ?? "Gateway error" }, { status: res.status });
  }
  return NextResponse.json({ ok: true });
}
