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

const Measurement = require('../src/measurements/Measurement.js');
const { near } = require('./helpers.js');

test('maintains rolling window and exposes stats', () => {
  const m = new Measurement('flow', 'measured', 'upstream', 3);
  m.setValue(10, 1).setValue(20, 2).setValue(30, 3).setValue(40, 4);

  assert.deepEqual(m.getAllValues().values, [20, 30, 40]);
  assert.deepEqual(m.getAllValues().timestamps, [2, 3, 4]);
  assert.equal(m.getCurrentValue(), 40);
  assert.equal(m.getAverage(), 30);
  assert.equal(m.getMin(), 20);
  assert.equal(m.getMax(), 40);
});

test('lag semantics: lag=1 is previous sample', () => {
  const m = new Measurement('flow', 'measured', 'upstream', 5);
  m.setValue(10, 100).setValue(20, 200).setValue(30, 300);

  assert.equal(m.getLaggedSample(0).value, 30);
  assert.equal(m.getLaggedSample(1).value, 20);
  assert.equal(m.getLaggedValue(1), 20);
});

test('convertTo converts values to target unit', () => {
  const m = new Measurement('flow', 'measured', 'upstream', 5);
  m.setUnit('m3/h');
  m.setValue(3.6, 1);

  const converted = m.convertTo('m3/s');
  assert.ok(near(converted.getCurrentValue(), 0.001, 1e-8));
  assert.equal(converted.unit, 'm3/s');
  assert.equal(converted.getLatestTimestamp(), 1);
});

test('createDifference aligns timestamps and subtracts downstream from upstream', () => {
  const up = new Measurement('pressure', 'measured', 'upstream', 10).setUnit('mbar');
  const down = new Measurement('pressure', 'measured', 'downstream', 10).setUnit('mbar');

  up.setValue(120, 1).setValue(140, 2);
  down.setValue(100, 2).setValue(95, 3);

  const diff = Measurement.createDifference(up, down);
  assert.deepEqual(diff.getAllValues().timestamps, [2]);
  assert.deepEqual(diff.getAllValues().values, [40]);
});
