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

const DashboardApi = require('../src/specificClass');

function makeNodeSource({ id, name, softwareType, positionVsParent, children = [] }) {
  const registeredChildren = new Map();
  for (const child of children) {
    registeredChildren.set(child.config.general.id, {
      child,
      softwareType: child.config.functionality.softwareType,
      position: child.positionVsParent || child.config.functionality.positionVsParent,
      registeredAt: Date.now(),
    });
  }

  return {
    config: {
      general: { id, name },
      functionality: { softwareType, positionVsParent },
    },
    positionVsParent,
    childRegistrationUtils: { registeredChildren },
  };
}

test('buildDashboard sets id=null, stable uid, title, measurement and bucket vars', () => {
  const api = new DashboardApi({
    general: { name: 'dashboardapi-test', logging: { enabled: false, logLevel: 'error' } },
    grafanaConnector: { protocol: 'http', host: 'localhost', port: 3000, bearerToken: '' },
  });

  const nodeSource = makeNodeSource({
    id: 'm-1',
    name: 'PT-1',
    softwareType: 'measurement',
    positionVsParent: 'downstream',
  });

  const dash = api.buildDashboard({ nodeConfig: nodeSource.config, positionVsParent: 'downstream' });

  assert.equal(dash.dashboard.id, null);
  assert.equal(dash.uid.length, 12);
  assert.equal(dash.dashboard.uid, dash.uid);
  assert.equal(dash.dashboard.title, 'PT-1');

  const templ = dash.dashboard.templating.list;
  const measurement = templ.find((v) => v.name === 'measurement');
  const bucket = templ.find((v) => v.name === 'bucket');

  assert.equal(measurement.current.value, 'measurement_m-1');
  assert.equal(bucket.current.value, 'lvl3');
});

test('generateDashboardsForGraph returns root + direct child dashboards and adds links', () => {
  const api = new DashboardApi({
    general: { name: 'dashboardapi-test', logging: { enabled: false, logLevel: 'error' } },
    grafanaConnector: { protocol: 'http', host: 'localhost', port: 3000, bearerToken: '' },
  });

  const child = makeNodeSource({
    id: 'c-1',
    name: 'ChildSensor',
    softwareType: 'measurement',
    positionVsParent: 'upstream',
  });

  const root = makeNodeSource({
    id: 'p-1',
    name: 'ParentMachine',
    softwareType: 'machine',
    positionVsParent: 'atEquipment',
    children: [child],
  });

  const results = api.generateDashboardsForGraph(root, { includeChildren: true });
  assert.equal(results.length, 2);

  const rootDash = results[0];
  assert.ok(Array.isArray(rootDash.dashboard.links));
  assert.ok(rootDash.dashboard.links.some((l) => l.url && l.url.includes('/d/')));
});
