import { describe, expect, it } from 'vitest';
import {
  toSafetyQuizComplianceRow,
  toSafetyQuizResultCreateDto,
} from '@/business/safety-quiz/mappers';
import {
  calculateSafetyQuizCompletionSummary,
  calculateSafetyQuizProgress,
  calculateSafetyQuizScore,
  getSafetyQuizFeedback,
} from '@/business/safety-quiz/selectors';
import type { SafetyQuizSubmission } from '@/business/safety-quiz/types';
import type { SafetyQuiz } from '@/shared/types/app';
import type { SafetyQuizResultDto } from '@/shared/types/safetyQuiz';

function createResult(overrides: Partial<SafetyQuizResultDto> = {}): SafetyQuizResultDto {
  return {
    id: 'result-1',
    quiz_id: 'quiz-1',
    quiz_title: 'QBS Week 1',
    week_of: '2026-06-08',
    score: 4,
    total_questions: 5,
    answers: [0, 1, 2, 3, 0],
    user_name: 'Ava Lee',
    user_role: 'support_staff',
    completed_at: '2026-06-08T12:00:00.000Z',
    organizationId: 'org-1',
    campusId: 'campus-1',
    userId: 'user-1',
    createdAt: '2026-06-08T12:00:00.000Z',
    updatedAt: '2026-06-08T12:00:00.000Z',
    ...overrides,
  };
}

describe('safety quiz mappers', () => {
  it('maps result DTOs to compliance rows with user-facing labels', () => {
    expect(toSafetyQuizComplianceRow(createResult())).toEqual({
      name: 'Ava Lee',
      role: 'Para',
      status: 'complete',
      score: '4/5',
      date: 'Jun 8',
    });
    expect(toSafetyQuizComplianceRow(createResult({ user_role: 'superintendent' })).role).toBe('Superintendent');
  });

  it('maps quiz submission to backend create DTO', () => {
    const submission: SafetyQuizSubmission = {
      quizId: 'quiz-1',
      quizTitle: 'QBS Week 1',
      weekOf: '2026-06-08',
      score: 4,
      totalQuestions: 5,
      answers: [0, 1, 2, 3, 0],
    };

    expect(toSafetyQuizResultCreateDto(submission)).toEqual({
      quiz_id: 'quiz-1',
      quiz_title: 'QBS Week 1',
      week_of: '2026-06-08',
      score: 4,
      total_questions: 5,
      answers: [0, 1, 2, 3, 0],
    });
  });
});

describe('safety quiz selectors', () => {
  const quiz: SafetyQuiz = {
    id: 'quiz-1',
    title: 'QBS Week 1',
    focus: 'de-escalation',
    weeklyFocus: {
      title: 'Focus',
      description: 'Description',
    },
    keyReminders: ['Reminder'],
    questions: [
      {
        id: 'question-1',
        question: 'Question 1',
        options: ['A', 'B'],
        correctIndex: 1,
        explanation: 'Explanation 1',
      },
      {
        id: 'question-2',
        question: 'Question 2',
        options: ['A', 'B'],
        correctIndex: 0,
        explanation: 'Explanation 2',
      },
    ],
  };

  it('calculates score and question progress', () => {
    expect(calculateSafetyQuizScore(quiz, [1, 1])).toBe(1);
    expect(calculateSafetyQuizProgress(0, 2)).toBe(50);
    expect(calculateSafetyQuizProgress(0, 0)).toBe(0);
  });

  it('returns result feedback by score', () => {
    expect(getSafetyQuizFeedback(2, 2)).toBe('Perfect score! Outstanding safety knowledge.');
    expect(getSafetyQuizFeedback(3, 5)).toBe('Great job! Review the explanations for any missed questions.');
    expect(getSafetyQuizFeedback(2, 5)).toBe('Please review the material and retake when ready.');
  });

  it('summarizes compliance rows', () => {
    expect(
      calculateSafetyQuizCompletionSummary([
        { name: 'Ava', role: 'Teacher', status: 'complete', score: '5/5', date: 'Jun 8' },
        { name: 'Ben', role: 'Para', status: 'complete', score: '4/5', date: 'Jun 8' },
      ]),
    ).toEqual({
      completedCount: 2,
      totalStaff: 2,
      completionRate: 100,
    });
  });
});
