// GET /api/pam/eligible
// Returns the roles the user can JIT-elevate to (from JWT *_eligible
// realm roles), enriched with policy config + whether a grant is
// already active.

import { auth } from "@/auth";
import { eligibleRoles } from "@/lib/authz";
import { prisma } from "@/database/prisma";

export const dynamic = "force-dynamic";

export async function GET() {
  const session = await auth();
  const user = session?.user as { gscSid?: string; roles?: string[] } | undefined;
  const gscsid = user?.gscSid;
  if (!gscsid) return Response.json({ error: "unauthorized" }, { status: 401 });

  const targetRoles = eligibleRoles({ roles: user!.roles ?? [] });
  if (targetRoles.length === 0) return Response.json({ eligible: [] });

  const [policies, activeGrants] = await Promise.all([
    prisma.privilegePolicy.findMany({
      where: { roleName: { in: targetRoles } },
      select: {
        roleName: true,
        maxDurationHours: true,
        defaultDurationHours: true,
        approvalMode: true,
        requiresMfa: true,
        description: true,
      },
    }),
    prisma.privilegeGrant.findMany({
      where: {
        gscsid,
        roleName: { in: targetRoles },
        status: "active",
        expiresAt: { gt: new Date() },
      },
      select: { roleName: true },
    }),
  ]);

  const policyByRole = new Map(policies.map((p) => [p.roleName, p]));
  const activeRoles = new Set(activeGrants.map((g) => g.roleName));

  return Response.json({
    eligible: targetRoles.map((role) => {
      const policy = policyByRole.get(role);
      return {
        role,
        policy: policy
          ? {
              approvalMode: policy.approvalMode,
              requiresMfa: policy.requiresMfa,
              maxDurationHours: policy.maxDurationHours,
              defaultDurationHours: policy.defaultDurationHours,
              description: policy.description,
            }
          : null,                          // role is eligible in IPA but no policy yet
        currentlyActive: activeRoles.has(role),
      };
    }),
  });
}
