import { describe, expect, it } from 'vitest';
import {
  canAccessModule,
  canAccessScopedModuleRoute,
  getAccessibleModuleId,
  getAccessibleModules,
  getScopedModules,
  getScopedModuleRouteRedirectPath,
  getSidebarCampusInitial,
  getSidebarRoleLabel,
  shouldShowMobileSidebarOverlay,
} from '@/business/app-shell/selectors';
import type { Module } from '@/shared/types/app';
import type { CurrentUser } from '@/shared/types/auth';

function user(permissions: readonly string[]): CurrentUser {
  return {
    id: 'user-1',
    email: 'user@example.com',
    app_role: { globalAccess: false },
    permissions,
  };
}

function globalUser(): CurrentUser {
  return {
    id: 'admin-1',
    email: 'admin@example.com',
    app_role: { name: 'super_admin', globalAccess: true },
    permissions: [],
  };
}

const modules: readonly Module[] = [
  {
    id: 'dashboard',
    name: 'Dashboard',
    icon: 'home',
    permissions: ['READ_DASHBOARD'],
    color: 'text-blue-400',
    routePath: '/dashboard',
  },
  {
    id: 'director',
    name: 'Director',
    icon: 'users',
    permissions: ['READ_DIRECTOR_DASHBOARD'],
    color: 'text-emerald-400',
    routePath: '/director-dashboard',
  },
];

const scopedModules: readonly Module[] = [
  { id: 'platform-dashboard', name: 'Platform', icon: 'chart', permissions: ['READ_PLATFORM_DASHBOARD'], color: '', routePath: '/platform-dashboard' },
  { id: 'dashboard', name: 'Dashboard', icon: 'home', permissions: ['READ_DASHBOARD'], color: '', routePath: '/dashboard' },
  { id: 'classroom', name: 'Classroom Support', icon: 'book', permissions: ['READ_CLASSROOM'], color: '', routePath: '/classroom-support' },
  { id: 'timer', name: 'Timer', icon: 'timer', permissions: ['READ_TIMER'], color: '', routePath: '/timer' },
  { id: 'qbs', name: 'Behavior Management', icon: 'shield', permissions: ['READ_QBS'], color: '', routePath: '/qbs-safety' },
  { id: 'zones', name: 'Zones', icon: 'layers', permissions: ['READ_ZONES'], color: '', routePath: '/zones-of-regulation' },
  { id: 'director', name: 'Director', icon: 'chart', permissions: ['READ_DIRECTOR_DASHBOARD'], color: '', routePath: '/director-dashboard' },
];

describe('app-shell selectors', () => {
  it('checks module access from effective permissions', () => {
    expect(canAccessModule(modules, 'dashboard', user(['READ_DASHBOARD']))).toBe(true);
    expect(canAccessModule(modules, 'director', user(['READ_DASHBOARD']))).toBe(false);
    expect(canAccessModule(modules, 'director', user(['READ_DIRECTOR_DASHBOARD']))).toBe(true);
  });

  it('falls back to dashboard when the requested module is unavailable', () => {
    expect(getAccessibleModuleId(modules, 'director', user(['READ_DASHBOARD']))).toBe('dashboard');
    expect(getAccessibleModuleId(modules, 'director', user(['READ_DIRECTOR_DASHBOARD']))).toBe('director');
  });

  it("returns modules available to the user's permissions", () => {
    expect(getAccessibleModules(modules, user(['READ_DASHBOARD'])).map((module) => module.id)).toEqual(['dashboard']);
    expect(getAccessibleModules(modules, user(['READ_DASHBOARD', 'READ_DIRECTOR_DASHBOARD'])).map((module) => module.id)).toEqual(['dashboard', 'director']);
  });

  it('scopes modules by effective tier on top of permission access', () => {
    expect(
      getScopedModules(scopedModules, user(['READ_DASHBOARD', 'READ_CLASSROOM', 'READ_TIMER']), 'class', false).map((m) => m.id),
    ).toEqual(['dashboard', 'classroom', 'timer']);

    expect(
      getScopedModules(scopedModules, user(['READ_DASHBOARD', 'READ_CLASSROOM', 'READ_TIMER', 'READ_ZONES', 'READ_DIRECTOR_DASHBOARD']), 'campus', false).map((m) => m.id),
    ).toEqual(['dashboard', 'classroom', 'zones', 'director']);
  });

  it('makes Classroom Support available from organization through class scopes', () => {
    const classroomUser = user(['READ_CLASSROOM']);

    expect(getScopedModules(scopedModules, classroomUser, 'organization', false).map((m) => m.id)).toEqual(['classroom']);
    expect(getScopedModules(scopedModules, classroomUser, 'school', false).map((m) => m.id)).toEqual(['classroom']);
    expect(getScopedModules(scopedModules, classroomUser, 'campus', false).map((m) => m.id)).toEqual(['classroom']);
    expect(getScopedModules(scopedModules, classroomUser, 'class', false).map((m) => m.id)).toEqual(['classroom']);
  });

  it('makes Behavior Management available at organization, campus, and class scopes', () => {
    const behaviorUser = user(['READ_QBS']);

    expect(getScopedModules(scopedModules, behaviorUser, 'organization', false).map((m) => m.id)).toEqual(['qbs']);
    expect(getScopedModules(scopedModules, behaviorUser, 'school', false).map((m) => m.id)).toEqual([]);
    expect(getScopedModules(scopedModules, behaviorUser, 'campus', false).map((m) => m.id)).toEqual(['qbs']);
    expect(getScopedModules(scopedModules, behaviorUser, 'class', false).map((m) => m.id)).toEqual(['qbs']);
  });

  it('never shows the Director Dashboard via drill-down', () => {
    expect(
      getScopedModules(scopedModules, user(['READ_DASHBOARD', 'READ_DIRECTOR_DASHBOARD']), 'campus', true).map((m) => m.id),
    ).toEqual(['dashboard']);
  });

  it('applies scope tiers to direct module route access', () => {
    expect(canAccessScopedModuleRoute(scopedModules, '/platform-dashboard', globalUser(), 'global', false)).toBe(true);
    expect(canAccessScopedModuleRoute(scopedModules, '/dashboard', globalUser(), 'global', false)).toBe(false);
    expect(canAccessScopedModuleRoute(scopedModules, '/zones-of-regulation', globalUser(), 'global', false)).toBe(false);
    expect(canAccessScopedModuleRoute(scopedModules, '/classroom-support', user(['READ_CLASSROOM']), 'organization', false)).toBe(true);
    expect(canAccessScopedModuleRoute(scopedModules, '/classroom-support', user(['READ_CLASSROOM']), 'school', false)).toBe(true);
    expect(canAccessScopedModuleRoute(scopedModules, '/qbs-safety', user(['READ_QBS']), 'organization', false)).toBe(true);
    expect(canAccessScopedModuleRoute(scopedModules, '/qbs-safety', user(['READ_QBS']), 'school', false)).toBe(false);
    expect(canAccessScopedModuleRoute(scopedModules, '/zones-of-regulation', user(['READ_ZONES']), 'class', false)).toBe(true);
  });

  it('redirects invalid module routes after effective scope changes', () => {
    expect(
      getScopedModuleRouteRedirectPath(
        scopedModules,
        '/platform-dashboard',
        globalUser(),
        'organization',
        true,
      ),
    ).toBe('/dashboard');

    expect(
      getScopedModuleRouteRedirectPath(
        scopedModules,
        '/dashboard',
        globalUser(),
        'global',
        false,
      ),
    ).toBe('/platform-dashboard');

    expect(
      getScopedModuleRouteRedirectPath(
        scopedModules,
        '/dashboard',
        user(['READ_DASHBOARD']),
        'organization',
        false,
      ),
    ).toBeNull();

    expect(
      getScopedModuleRouteRedirectPath(
        scopedModules,
        '/profile',
        user(['READ_DASHBOARD']),
        'organization',
        false,
      ),
    ).toBeNull();
  });

  it('formats sidebar role labels through shared auth role labels', () => {
    expect(getSidebarRoleLabel('support_staff')).toBe('Support Staff');
    expect(getSidebarRoleLabel('office_manager')).toBe('Office Manager');
  });

  it('returns a campus initial when campus branding is available', () => {
    expect(getSidebarCampusInitial({
      id: 'campus-1',
      mascot: 'Tigers',
      fullName: 'Tigers Campus',
      color: 'bg-orange-500',
      bgGradient: 'from-orange-500 to-amber-500',
      borderColor: 'border-orange-500/30',
      textColor: 'text-orange-400',
      bgLight: 'bg-orange-500/10',
      description: 'Campus branding',
    })).toBe('T');
    expect(getSidebarCampusInitial()).toBeNull();
  });

  it('shows the mobile sidebar overlay only when mobile sidebar is open on mobile', () => {
    expect(shouldShowMobileSidebarOverlay(true, true)).toBe(true);
    expect(shouldShowMobileSidebarOverlay(true, false)).toBe(false);
    expect(shouldShowMobileSidebarOverlay(false, true)).toBe(false);
  });
});
