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

const moduleEntrypoints = [
  'public/js/calculators.js',
  'public/js/chartReview.js',
  'public/js/clinicalAssistant.js',
  'public/js/admin.js',
  'public/js/admin-docs.js',
  'public/js/audioBackup.js',
  'public/js/authFetch.js',
  'public/js/diagrams.js',
  'public/js/drugs-loader.js',
  'public/js/ed-encounters.js',
  'public/js/extensions.js',
  'public/js/hospitalCourse.js',
  'public/js/learningHub.js',
  'public/js/memories.js',
  'public/js/milestones.js',
  'public/js/nextcloud.js',
  'public/js/notes.js',
  'public/js/peGuide.js',
  'public/js/sickVisit.js',
  'public/js/soap.js',
  'public/js/secureStorage.js',
  'public/js/speechRecognition.js',
  'public/js/transcriptionSettings.js',
  'public/js/ui-state.js',
  'public/js/wellVisit.js',
  'public/js/voicePreferences.js',
  'public/js/documents.js'
];

const iifeFreeEntrypoints = [
  ...moduleEntrypoints,
  'public/js/app.js'
];

function readProjectFile(relativePath) {
  return fs.readFileSync(path.join(__dirname, '..', relativePath), 'utf8');
}

test('refactored frontend entrypoints are loaded as modules', () => {
  const indexHtml = readProjectFile('public/index.html');
  moduleEntrypoints.forEach((entrypoint) => {
    const src = '/' + entrypoint.replace(/^public\//, '');
    const pattern = new RegExp('<script\\s+type="module"\\s+src="' + src.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?:\\?v=[^\"]+)?"><\\/script>');
    assert.match(indexHtml, pattern, `${src} should be loaded as a module`);
  });
});

test('refactored module entrypoints do not use redundant IIFE wrappers', () => {
  iifeFreeEntrypoints.forEach((entrypoint) => {
    const source = readProjectFile(entrypoint);
    assert.doesNotMatch(source, /^\s*\(function\s*\(/m, `${entrypoint} should not open an IIFE wrapper`);
    assert.doesNotMatch(source, /^\s*\}\)\(\);\s*$/m, `${entrypoint} should not close an IIFE wrapper`);
  });
});
