import test from 'node:test';
import assert from 'node:assert/strict';
import {
  beginRuntimeDrain,
  endRuntimeDrain,
  getRuntimeDrainSnapshot,
  isRuntimeDraining,
  trackHttpRequestFinished,
  trackHttpRequestStarted,
  trackWebSocketConnectionClosed,
  trackWebSocketConnectionOpened,
} from './runtime-drain-service.js';

test('runtime drain service tracks drain and connection counters without going negative', () => {
  endRuntimeDrain();
  trackHttpRequestFinished();
  trackWebSocketConnectionClosed();

  assert.equal(isRuntimeDraining(), false);
  assert.equal(getRuntimeDrainSnapshot().activeHttpRequestCount, 0);
  assert.equal(getRuntimeDrainSnapshot().activeWebSocketConnectionCount, 0);

  beginRuntimeDrain();
  trackHttpRequestStarted();
  trackHttpRequestStarted();
  trackWebSocketConnectionOpened();

  assert.equal(isRuntimeDraining(), true);
  assert.equal(getRuntimeDrainSnapshot().activeHttpRequestCount, 2);
  assert.equal(getRuntimeDrainSnapshot().activeWebSocketConnectionCount, 1);

  trackHttpRequestFinished();
  trackHttpRequestFinished();
  trackHttpRequestFinished();
  trackWebSocketConnectionClosed();
  trackWebSocketConnectionClosed();
  endRuntimeDrain();

  const snapshot = getRuntimeDrainSnapshot();
  assert.equal(snapshot.draining, false);
  assert.equal(snapshot.drainStartedAt, null);
  assert.equal(snapshot.activeHttpRequestCount, 0);
  assert.equal(snapshot.activeWebSocketConnectionCount, 0);
});
