import { createContext, useContext } from 'react';

import type { ScopeTier } from '@/business/scope/selectors';
import type { ActiveTenant, TenantChild } from '@/shared/types/scope';

export interface ScopeContextValue {
  /** The signed-in user's authorization tier. */
  readonly tier: ScopeTier;
  /** The user's own tenant (their scope level). */
  readonly ownTenant: ActiveTenant | null;
  /** A drilled-into child tenant, or null when viewing the user's own scope. */
  readonly selectedTenant: ActiveTenant | null;
  /** selectedTenant ?? ownTenant — the tenant whose data pages should show. */
  readonly effectiveTenant: ActiveTenant | null;
  /** Whether this tier can drill into child tenants. */
  readonly canDrill: boolean;
  readonly drillInto: (child: TenantChild) => void;
  readonly setScopeTenant: (tenant: ActiveTenant | null) => void;
  readonly resetScope: () => void;
}

export const ScopeContext = createContext<ScopeContextValue>({
  tier: 'external',
  ownTenant: null,
  selectedTenant: null,
  effectiveTenant: null,
  canDrill: false,
  drillInto: () => {},
  setScopeTenant: () => {},
  resetScope: () => {},
});

export const useScopeContext = (): ScopeContextValue => useContext(ScopeContext);
