import { decodeJwtPayload } from "@/lib/auth/jwt-claims"

function normalizeGroups(claims: Record<string, unknown>): string[] {
  const raw = claims.groups ?? claims.roles
  if (!Array.isArray(raw)) return []
  return raw
    .filter((g): g is string => typeof g === "string")
    .map((g) => g.trim().toLowerCase())
}

/** Platform admin from OIDC groups (`admin`, `role:admin`). */
export function isPlatformAdminFromToken(token: string | null | undefined): boolean {
  if (!token) return false
  const claims = decodeJwtPayload(token)
  if (!claims) return false
  return normalizeGroups(claims).some((g) => g === "admin" || g === "role:admin")
}

export function adminScopesFromToken(token: string | null | undefined): {
  read: boolean
  write: boolean
} {
  if (!token) return { read: false, write: false }
  if (isPlatformAdminFromToken(token)) return { read: true, write: true }
  const groups = normalizeGroups(decodeJwtPayload(token) ?? {})
  return {
    read: groups.includes("admin:read") || groups.includes("admin:write"),
    write: groups.includes("admin:write"),
  }
}
