import { useMemo } from 'react';

import { setActiveTenant } from '@/shared/api/httpClient';
import {
  getActiveTenant,
  getScopeTier,
  getScopeTierLabel,
  type ScopeTier,
} from '@/business/scope/selectors';
import type { CurrentUser } from '@/shared/types/auth';
import type { ActiveTenant } from '@/shared/types/scope';

export interface ScopeState {
  readonly tier: ScopeTier;
  readonly tierLabel: string;
  readonly activeTenant: ActiveTenant | null;
}

/**
 * Derives the signed-in user's scope tier and active tenant from the auth
 * session. Pure function of the user object — call from the view layer with
 * the authenticated user.
 */
export function useScope(user: CurrentUser | null | undefined): ScopeState {
  return useMemo(() => {
    const tier = getScopeTier(user);
    return {
      tier,
      tierLabel: getScopeTierLabel(tier),
      activeTenant: getActiveTenant(user),
    };
  }, [user]);
}

/**
 * Sets the active tenant for API requests (used by ScopeProvider to sync
 * drill-down state to the HTTP client).
 */
export function setActiveTenantForApi(
  value: { readonly level: string; readonly id: string } | null,
): void {
  setActiveTenant(value);
}
