// POST /api/pam/revoke/[id] — self-revoke an active grant.
//
// Only the owner can revoke their own grant via this endpoint. An
// admin override path would live elsewhere (e.g. /api/pam/admin/...)
// once we add it.

import { auth } from "@/auth";
import { prisma } from "@/database/prisma";
import { revokeGrant } from "@/lib/pam";

export const dynamic = "force-dynamic";

export async function POST(req: Request, ctx: { params: Promise<{ id: string }> }) {
  const session = await auth();
  const user = session?.user as { gscSid?: string } | undefined;
  const gscsid = user?.gscSid;
  if (!gscsid) return Response.json({ error: "unauthorized" }, { status: 401 });

  const { id } = await ctx.params;
  const grant = await prisma.privilegeGrant.findUnique({
    where: { id },
    select: { gscsid: true, status: true },
  });
  if (!grant) return Response.json({ error: "not_found" }, { status: 404 });
  if (grant.gscsid !== gscsid) {
    return Response.json({ error: "forbidden" }, { status: 403 });
  }

  let reason: string | null = null;
  try {
    const body = await req.json().catch(() => ({}));
    if (body && typeof body.reason === "string") reason = body.reason.slice(0, 500);
  } catch {
    /* no body, fine */
  }

  await revokeGrant(id, gscsid, reason);
  return Response.json({ status: "revoked" });
}
