import { describe, it, expect } from 'vitest';
import { generateQuiz } from './quiz';
import type { GlossaryEntry } from './glossary';

const entry = (term: string, definition: string, start = 0): GlossaryEntry => ({
  term,
  definition,
  start,
  segmentId: `seg-${term}`,
});

const FOUR: GlossaryEntry[] = [
  entry('Alpha', 'the first letter'),
  entry('Beta', 'the second letter'),
  entry('Gamma', 'the third letter'),
  entry('Delta', 'the fourth letter'),
];

describe('generateQuiz', () => {
  it('returns [] when there are fewer than 4 terms', () => {
    expect(generateQuiz(FOUR.slice(0, 3))).toEqual([]);
    expect(generateQuiz([])).toEqual([]);
  });

  it('returns [] when count <= 0', () => {
    expect(generateQuiz(FOUR, { count: 0 })).toEqual([]);
  });

  it('each question has 4 options with the answer at answerIndex', () => {
    const quiz = generateQuiz(FOUR);
    expect(quiz.length).toBe(4);
    for (let i = 0; i < quiz.length; i++) {
      const q = quiz[i]!;
      const src = FOUR[i]!;
      expect(q.options.length).toBe(4);
      // The option at answerIndex is the correct term for that question.
      expect(q.options[q.answerIndex]).toBe(src.term);
      // Question wraps the correct definition.
      expect(q.question).toBe(`Which term means: "${src.definition}"?`);
    }
  });

  it('uses deterministic answer placement at index i % 4', () => {
    const quiz = generateQuiz(FOUR);
    expect(quiz.map((q) => q.answerIndex)).toEqual([0, 1, 2, 3]);
  });

  it('options are distinct and include 3 distractors from other entries', () => {
    const quiz = generateQuiz(FOUR);
    for (const q of quiz) {
      const unique = new Set(q.options.map((o) => o.toLowerCase()));
      expect(unique.size).toBe(4);
    }
  });

  it('carries start and segmentId from the correct entry', () => {
    const quiz = generateQuiz(FOUR);
    expect(quiz[0]!.segmentId).toBe('seg-Alpha');
    expect(quiz[0]!.start).toBe(0);
  });

  it('respects the count cap', () => {
    const quiz = generateQuiz(FOUR, { count: 2 });
    expect(quiz.length).toBe(2);
  });
});
