import { NextRequest, NextResponse } from "next/server";
import { deleteServer, updateServer } from "@/lib/server/xtreamServers";

export const dynamic = "force-dynamic";

function adminOk(req: NextRequest): boolean {
  const key = process.env.ARVIO_ADMIN_KEY || "admin123";
  return (req.headers.get("x-admin-key") || "") === key;
}

export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  if (!adminOk(req)) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
  const { id } = await ctx.params;
  const body = await req.json().catch(() => ({}));
  const patch: Record<string, unknown> = {};
  if (typeof body.active === "boolean") patch.active = body.active;
  if (typeof body.label === "string") patch.label = body.label;
  if (typeof body.order === "number") patch.order = body.order;
  await updateServer(id, patch);
  return NextResponse.json({ ok: true });
}

export async function DELETE(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  if (!adminOk(req)) return NextResponse.json({ error: "No autorizado" }, { status: 401 });
  const { id } = await ctx.params;
  await deleteServer(id);
  return NextResponse.json({ ok: true });
}
