import { describe, expect, it } from 'vitest';
import {
  canCreateCommunicationEvents,
  filterCommunicationEventsByRole,
  getTemplateCategory,
  toCommunicationEventType,
} from '@/business/communications/selectors';
import type { CommunicationEventDto, ParentTemplate } from '@/shared/types/communications';

function createEvent(
  overrides: Partial<CommunicationEventDto> = {},
): CommunicationEventDto {
  return {
    id: 'event-1',
    title: 'Safety drill',
    date: '2026-06-08',
    type: 'drill',
    roles: ['director', 'teacher'],
    organizationId: 'org-1',
    campusId: 'campus-1',
    createdById: 'user-1',
    updatedById: null,
    createdAt: '2026-06-08T10:00:00.000Z',
    updatedAt: '2026-06-08T10:00:00.000Z',
    ...overrides,
  };
}

describe('communication selectors', () => {
  it('allows only director and superintendent roles to create events', () => {
    expect(canCreateCommunicationEvents('director')).toBe(true);
    expect(canCreateCommunicationEvents('superintendent')).toBe(true);
    expect(canCreateCommunicationEvents('teacher')).toBe(false);
    expect(canCreateCommunicationEvents('support_staff')).toBe(false);
    expect(canCreateCommunicationEvents('office_manager')).toBe(false);
  });

  it('resolves selected template category and falls back to general', () => {
    const templates: readonly ParentTemplate[] = [
      { id: 'progress', template: 'Progress note', category: 'progress' },
      { id: 'event', template: 'Event note', category: 'event' },
    ];

    expect(getTemplateCategory('progress', templates)).toBe('progress');
    expect(getTemplateCategory('missing', templates)).toBe('general');
    expect(getTemplateCategory(null, templates)).toBe('general');
  });

  it('filters communication events by visible user role', () => {
    const events = [
      createEvent({ id: 'teacher-event', roles: ['teacher'] }),
      createEvent({ id: 'director-event', roles: ['director', 'superintendent'] }),
      createEvent({ id: 'office-event', roles: ['office_manager'] }),
    ];

    expect(filterCommunicationEventsByRole(events, 'director')).toEqual([events[1]]);
    expect(filterCommunicationEventsByRole(events, 'office_manager')).toEqual([events[2]]);
  });

  it('normalizes unsupported event types to meeting', () => {
    expect(toCommunicationEventType('deadline')).toBe('deadline');
    expect(toCommunicationEventType('unsupported')).toBe('meeting');
  });
});
