import type { CurrentUser } from '@/shared/types/auth';
import type { ActiveTenant } from '@/shared/types/scope';

/** Authorization tier of the signed-in user (derived from `app_role.scope`). */
export type ScopeTier =
  | 'global'
  | 'organization'
  | 'school'
  | 'campus'
  | 'class'
  | 'external';

export function getScopeTier(user: CurrentUser | null | undefined): ScopeTier {
  if (!user) return 'external';
  if (user.app_role?.globalAccess) return 'global';
  switch (user.app_role?.scope) {
    case 'system':
      return 'global';
    case 'organization':
      return 'organization';
    case 'school':
      return 'school';
    case 'campus':
      return 'campus';
    case 'class':
      return 'class';
    default:
      return 'external';
  }
}

const SCOPE_TIER_LABELS: Record<ScopeTier, string> = {
  global: 'Platform',
  organization: 'Organization',
  school: 'School',
  campus: 'Campus',
  class: 'Classroom',
  external: 'External',
};

export function getScopeTierLabel(tier: ScopeTier): string {
  return SCOPE_TIER_LABELS[tier];
}

/**
 * The user's own active tenant — the tenant at their scope tier. Campuses carry
 * no logo (name only); schools/classes/orgs may carry one.
 */
export function getActiveTenant(
  user: CurrentUser | null | undefined,
): ActiveTenant | null {
  if (!user) return null;
  const tier = getScopeTier(user);

  if (tier === 'class' && user.classRoom?.id) {
    return { level: 'class', id: user.classRoom.id, name: user.classRoom.name ?? null, logo: user.classRoom.logo ?? null };
  }
  if (tier === 'campus' && user.campus?.id) {
    return { level: 'campus', id: user.campus.id, name: user.campus.name ?? null, logo: null };
  }
  if (tier === 'school' && user.school?.id) {
    return { level: 'school', id: user.school.id, name: user.school.name ?? null, logo: user.school.logo ?? null };
  }
  if (user.organizations?.id) {
    return { level: 'organization', id: user.organizations.id, name: user.organizations.name ?? null, logo: null };
  }
  return null;
}

/** Two-letter initials for a tenant name, used as a logo fallback. */
export function getTenantInitials(name: string | null): string {
  if (!name) return '–';
  const words = name.trim().split(/\s+/).filter(Boolean);
  if (words.length === 0) return '–';
  if (words.length === 1) return words[0].slice(0, 2).toUpperCase();
  return (words[0][0] + words[words.length - 1][0]).toUpperCase();
}

/**
 * Personal saved states are reportable user data. They are valid only when the
 * user is viewing their own tenant, not while a parent user is drilled into a
 * child tenant.
 */
export function canPersistPersonalScopeResults(
  ownTenant: ActiveTenant | null,
  selectedTenant: ActiveTenant | null,
): boolean {
  if (!selectedTenant) {
    return true;
  }

  return Boolean(
    ownTenant
      && ownTenant.level === selectedTenant.level
      && ownTenant.id === selectedTenant.id,
  );
}
