import type { ReactNode } from 'react';
import { usePermissions } from '@/hooks/usePermissions';
import type { PermissionName } from '@/shared/auth/permissions';

interface PermissionGateProps {
  /** Require this single permission. */
  readonly permission?: PermissionName;
  /** Require at least one of these permissions. */
  readonly anyOf?: readonly PermissionName[];
  /** Require all of these permissions. */
  readonly allOf?: readonly PermissionName[];
  /** Rendered when the user is not permitted (defaults to nothing). */
  readonly fallback?: ReactNode;
  readonly children: ReactNode;
}

/**
 * Renders its children only when the current user holds the required
 * permission(s) (Workstream 3 §3.6). UX-only — the backend still enforces every
 * request; this just hides affordances the backend would reject. `globalAccess`
 * roles pass (handled by the selectors).
 */
export function PermissionGate({
  permission,
  anyOf,
  allOf,
  fallback = null,
  children,
}: PermissionGateProps) {
  const permissions = usePermissions();

  const allowed =
    (permission === undefined || permissions.has(permission)) &&
    (anyOf === undefined || permissions.hasAny(anyOf)) &&
    (allOf === undefined || permissions.hasAll(allOf));

  return <>{allowed ? children : fallback}</>;
}
