const test = require('node:test');
const assert = require('node:assert/strict');

const ChildRegistrationUtils = require('../src/helper/childRegistrationUtils.js');

function makeMainClass() {
  return {
    logger: {
      debug() {},
      info() {},
      warn() {},
      error() {},
    },
    child: {},
    registerChildCalls: [],
    registerChild(child, softwareType) {
      this.registerChildCalls.push({ child, softwareType });
    },
  };
}

test('registerChild wires parent, measurement context, and storage', async () => {
  const mainClass = makeMainClass();
  const utils = new ChildRegistrationUtils(mainClass);

  const measurementContext = {
    childId: null,
    childName: null,
    parentRef: null,
    setChildId(v) { this.childId = v; },
    setChildName(v) { this.childName = v; },
    setParentRef(v) { this.parentRef = v; },
  };

  const child = {
    config: {
      functionality: { softwareType: 'measurement' },
      general: { name: 'PT1', id: 'child-1' },
      asset: { category: 'sensor' },
    },
    measurements: measurementContext,
  };

  await utils.registerChild(child, 'upstream');

  assert.deepEqual(child.parent, [mainClass]);
  assert.equal(child.positionVsParent, 'upstream');
  assert.equal(measurementContext.childId, 'child-1');
  assert.equal(measurementContext.childName, 'PT1');
  assert.equal(measurementContext.parentRef, mainClass);

  assert.equal(mainClass.child.measurement.sensor.length, 1);
  assert.equal(utils.getChildById('child-1'), child);
  assert.equal(mainClass.registerChildCalls.length, 1);
});
