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

function loadScheduleJson() {
  const raw = fs.readFileSync(path.join(__dirname, '..', 'public', 'data', 'well-visit', 'schedule.json'), 'utf8');
  return JSON.parse(raw);
}

test('schedule.json exposes complete well-visit schedule data', () => {
  const json = loadScheduleJson();

  assert.equal(json.version, '2025.1');
  assert.ok(Array.isArray(json.visitAges));
  assert.ok(json.wellVisitCodes && json.wellVisitCodes['2mo']);
  assert.ok(json.vaccines && json.vaccines.DTaP);
  assert.ok(json.periodicity && json.periodicity['12mo']);
  assert.ok(json.catchUpSchedule && json.catchUpSchedule.DTaP);
  assert.ok(json.anticipatoryGuidance && json.anticipatoryGuidance.newborn_to_1mo);
  assert.ok(json.aapFootnotes && json.aapFootnotes['1']);
  assert.ok(json.dyslipidemiaSchedule && json.dyslipidemiaSchedule.universal);
  assert.ok(json.newbornScreening && json.newbornScreening.mandatoryComponents);
  assert.ok(json.growthReference && json.growthReference['2mo']);
  assert.ok(json.reflexesReference && json.reflexesReference.newborn);
  assert.ok(json.bmiClassification && Array.isArray(json.bmiClassification.categories));
});

test('schedule.json preserves expected well-visit anchors', () => {
  const data = loadScheduleJson();

  assert.equal(data.visitAges.length, 32);
  assert.deepEqual(data.visitAges[0], { id: 'prenatal', label: 'Prenatal', era: 'prenatal' });
  assert.deepEqual(data.visitAges[data.visitAges.length - 1], { id: '21y', label: '21 Years', era: 'adolescence' });
  assert.equal(data.wellVisitCodes['2mo'].cpt, '99391');
  assert.equal(data.periodicity['12mo'].procedures.lead, 'dot_or_risk');
  assert.equal(data.periodicity['11y'].developmental.depressionSuicideRisk, 'dot');
  assert.equal(data.catchUpSchedule.DTaP.series[4].minimumAge, '4 years');
  assert.equal(data.growthReference['2mo'].feeding.length, 4);
  assert.equal(data.reflexesReference.newborn.reflexes[2].name, 'Moro (startle)');
  assert.equal(data.bmiClassification.categories[3].label, 'Obesity (Class I)');
});

test('well-visit schedule loader fetches JSON and can apply legacy globals', async () => {
  const data = loadScheduleJson();
  const previousFetch = globalThis.fetch;
  globalThis.fetch = async function(url, options) {
    assert.equal(url, '/data/well-visit/schedule.json');
    assert.deepEqual(options, { credentials: 'same-origin' });
    return {
      ok: true,
      async json() {
        return data;
      }
    };
  };

  try {
    const module = await import('../public/js/wellVisit/scheduleData.js');
    const loaded = await module.loadWellVisitScheduleData();
    assert.strictEqual(loaded, data);

    const target = {};
    module.applyWellVisitScheduleGlobals(loaded, target);
    assert.strictEqual(target.VISIT_AGES, data.visitAges);
    assert.strictEqual(target.PERIODICITY, data.periodicity);
    assert.strictEqual(target.CATCH_UP_SCHEDULE, data.catchUpSchedule);
    assert.strictEqual(target.BMI_CLASSIFICATION, data.bmiClassification);
  } finally {
    globalThis.fetch = previousFetch;
  }
});

test('index loads wellVisit as a module without the legacy schedule data script', () => {
  const indexHtml = fs.readFileSync(path.join(__dirname, '..', 'public', 'index.html'), 'utf8');
  assert.match(indexHtml, /<script type="module" src="\/js\/wellVisit\.js"><\/script>/);
  assert.doesNotMatch(indexHtml, /src="\/js\/pediatricScheduleData\.js"/);
});

test('server well-visit route reads schedule JSON instead of legacy browser data file', () => {
  const source = fs.readFileSync(path.join(__dirname, '..', 'src', 'routes', 'wellVisit.js'), 'utf8');
  assert.match(source, /public\/data\/well-visit\/schedule\.json/);
  assert.doesNotMatch(source, /pediatricScheduleData/);
});
