import { describe, expect, it } from 'vitest';
import {
  buildTopBarSearchResults,
  searchContentItems,
  searchModules,
  type TopBarContentItem,
} from '@/business/top-bar/search';
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,
  };
}

const modules: Module[] = [
  { id: 'dashboard', name: 'Home Dashboard', icon: 'home', permissions: ['READ_DASHBOARD'], color: '', routePath: '/dashboard' },
  { id: 'zones', name: 'Regulate your Zone', icon: 'layers', permissions: ['READ_ZONES'], color: '', routePath: '/zones-of-regulation' },
  { id: 'director', name: 'Director Dashboard', icon: 'chart', permissions: ['READ_DIRECTOR_DASHBOARD'], color: '', routePath: '/director-dashboard' },
];

const content: TopBarContentItem[] = [
  { id: 's1', label: 'Visual Schedule Boards', moduleId: 'classroom', moduleName: 'Classroom Support' },
  { id: 'w1', label: 'Help', moduleId: 'signs', moduleName: 'Sign Language' },
];

describe('top bar search', () => {
  it('matches only accessible modules by name/id (case-insensitive)', () => {
    const results = searchModules(modules, user(['READ_DASHBOARD', 'READ_ZONES']), 'dash');
    expect(results.map((result) => result.moduleId)).toEqual(['dashboard']);
    // a teacher cannot see the director dashboard even though it matches "dash"
    expect(results.some((result) => result.moduleId === 'director')).toBe(false);
    // empty query → nothing
    expect(searchModules(modules, user(['READ_DASHBOARD']), '   ')).toEqual([]);
  });

  it('matches content items by label and carries the owning module', () => {
    const results = searchContentItems(content, 'visual');
    expect(results).toHaveLength(1);
    expect(results[0]).toMatchObject({ kind: 'content', moduleId: 'classroom', sublabel: 'Classroom Support' });
  });

  it('combines modules first, then content, capped', () => {
    const results = buildTopBarSearchResults(modules, user(['READ_DASHBOARD', 'READ_ZONES']), 'e', content, 2);
    expect(results).toHaveLength(2);
    expect(results[0]?.kind).toBe('module');
    expect(buildTopBarSearchResults(modules, user(['READ_DASHBOARD']), '', content)).toEqual([]);
  });
});
