import { describe, expect, it } from 'vitest';

import {
  buildDirectorFramePreviews,
  buildDirectorOverviewCards,
  buildDirectorRiskAreas,
  calculateQuizCompletionRate,
} from '@/business/director-dashboard/selectors';
import type { FrameEntryViewModel } from '@/business/frame/types';
import type { StaffAttendanceRecordViewModel } from '@/business/staff-attendance/types';
import type { SafetyQuizResultDto } from '@/shared/types/safetyQuiz';

function createAttendanceRecord(
  overrides: Partial<StaffAttendanceRecordViewModel> = {},
): StaffAttendanceRecordViewModel {
  return {
    id: 'attendance-1',
    date: '2026-06-01',
    status: 'present',
    note: null,
    userName: 'Ava Lee',
    userRole: 'teacher',
    ...overrides,
  };
}

function createQuizResult(overrides: Partial<SafetyQuizResultDto> = {}): SafetyQuizResultDto {
  return {
    id: 'quiz-1',
    quiz_id: 'qbs',
    quiz_title: 'QBS Safety',
    week_of: '2026-06-01',
    score: 5,
    total_questions: 5,
    answers: [0, 1, 2],
    user_name: 'Ava Lee',
    user_role: 'teacher',
    completed_at: '2026-06-01T09:00:00.000Z',
    organizationId: 'org-1',
    campusId: 'campus-1',
    userId: 'user-1',
    createdAt: '2026-06-01T09:00:00.000Z',
    updatedAt: '2026-06-01T09:00:00.000Z',
    ...overrides,
  };
}

function createFrameEntry(overrides: Partial<FrameEntryViewModel> = {}): FrameEntryViewModel {
  return {
    id: 'frame-1',
    weekOf: '2026-06-01',
    postedDate: 'June 1, 2026',
    formal: 'Formal learning focus for the week',
    recognition: 'Recognition focus for the week',
    application: 'Application focus for the week',
    management: 'Management focus for the week',
    emotional: 'Emotional learning focus for the week',
    author: 'Director',
    ...overrides,
  };
}

describe('director dashboard selectors', () => {
  it('calculates quiz completion rate with empty staff protection', () => {
    expect(calculateQuizCompletionRate([createQuizResult()], 0)).toBe(0);
    expect(calculateQuizCompletionRate([createQuizResult()], 4)).toBe(25);
  });

  it('builds overview cards from backend-backed records', () => {
    const cards = buildDirectorOverviewCards(
      [
        createAttendanceRecord({ id: 'present', status: 'present' }),
        createAttendanceRecord({ id: 'absent', status: 'absent' }),
      ],
      [createQuizResult()],
      [createFrameEntry()],
      2,
    );

    expect(cards.map((card) => card.value)).toEqual(['50%', '1/2', '1', '2']);
    expect(cards.map((card) => card.module)).toEqual(['attendance', 'qbs', 'frame', 'attendance']);
  });

  it('flags dashboard risk levels from quiz completion and absences', () => {
    const risks = buildDirectorRiskAreas(
      [
        createAttendanceRecord({ id: '1', status: 'absent' }),
        createAttendanceRecord({ id: '2', status: 'absent' }),
        createAttendanceRecord({ id: '3', status: 'absent' }),
        createAttendanceRecord({ id: '4', status: 'absent' }),
      ],
      [createQuizResult()],
      6,
    );

    expect(risks).toEqual([
      {
        issue: "5 staff haven't completed de-escalation quiz",
        severity: 'high',
        module: 'qbs',
      },
      {
        issue: '4 absences recorded this period',
        severity: 'high',
        module: 'attendance',
      },
    ]);
  });

  it('limits and truncates FRAME previews', () => {
    const longText = 'A'.repeat(70);
    const previews = buildDirectorFramePreviews([
      createFrameEntry({ id: '1', formal: longText }),
      createFrameEntry({ id: '2' }),
      createFrameEntry({ id: '3' }),
      createFrameEntry({ id: '4' }),
    ]);

    expect(previews).toHaveLength(3);
    expect(previews[0].sections[0]).toEqual({
      letter: 'F',
      text: `${'A'.repeat(60)}...`,
    });
  });
});
