import {
  permissionGranted,
  type Capability,
  type GlobalCapability,
  type PermissionGrant,
  type Team,
  type TeamCapability,
} from '@pig/core';

export interface PermissionIdentity {
  permissions: PermissionGrant[];
}

export function can(identity: PermissionIdentity | undefined, capability: GlobalCapability): boolean;
export function can(
  identity: PermissionIdentity | undefined,
  capability: TeamCapability,
  team: Team,
): boolean;
export function can(
  identity: PermissionIdentity | undefined,
  capability: GlobalCapability | TeamCapability,
  team?: Team,
): boolean {
  return Boolean(identity && permissionGranted(identity.permissions, capability, team));
}

/**
 * "Could this person do it on *any* team?"
 *
 * Distinct from `can()` on purpose. `can()` asks about a specific team, which
 * is what a button on a specific record needs. Navigation has no record and no
 * team yet — the question there is only whether the page could ever be useful
 * — and answering it by picking an arbitrary team would hide Import from
 * someone who is an admin of the one team that was not picked.
 */
export function canAny(
  identity: PermissionIdentity | undefined,
  capability: Capability,
): boolean {
  return Boolean(identity && permissionGranted(identity.permissions, capability));
}
