const { test } = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const { pathToFileURL } = require('node:url');

async function loadQuizController() {
  return import(pathToFileURL(path.join(__dirname, '..', 'public/js/learningHub/quizController.js')).href);
}

function makeRoot(singleSelections, multiSelections) {
  return {
    querySelector(selector) {
      var match = selector.match(/input\[name="lh-q-(\d+)"\]:checked/);
      if (!match) return null;
      var value = singleSelections[match[1]];
      return value == null ? null : { value: String(value) };
    },
    querySelectorAll(selector) {
      var match = selector.match(/input\[name="lh-qm-(\d+)"\]:checked/);
      if (!match) return [];
      return (multiSelections[match[1]] || []).map(function(value) { return { value: String(value) }; });
    }
  };
}

test('Learning Hub quiz answers preserve single, unanswered, and multi-select payloads', async () => {
  const { buildQuizAnswers } = await loadQuizController();
  const questions = [
    { id: 11, question_type: 'mcq' },
    { id: 12, question_type: 'true_false' },
    { id: 13, question_type: 'multi' },
    { id: 14, question_type: 'multi' }
  ];
  const root = makeRoot({ 11: 101 }, { 13: [301, 303] });

  assert.deepEqual(buildQuizAnswers(questions, root), [
    { questionId: 11, optionId: 101 },
    { questionId: 12, optionId: null },
    { questionId: 13, optionIds: [301, 303] },
    { questionId: 14, optionIds: [] }
  ]);
});

test('Learning Hub quiz controller keeps result highlighting semantics', async () => {
  const fs = require('node:fs');
  const source = fs.readFileSync(path.join(__dirname, '..', 'public/js/learningHub/quizController.js'), 'utf8');

  assert.match(source, /function applyQuizResultHighlights\(results\)/);
  assert.match(source, /var correctIds = r\.correctOptionIds \|\| \[\]/);
  assert.match(source, /var selectedIds = r\.selectedOptionIds \|\| \[\]/);
  assert.match(source, /selectedIds\.indexOf\(optId\) !== -1 && correctIds\.indexOf\(optId\) === -1/);
  assert.match(source, /optId === r\.correctOptionId/);
  assert.match(source, /optId === r\.selectedOptionId && !r\.isCorrect/);
  assert.match(source, /input\.disabled = true/);
});
