#!/usr/bin/env node
import assert from 'assert';
import net from 'net';
import { findFreePort } from './src/server/helpers.js';

function listenEphemeral() {
  return new Promise((resolve, reject) => {
    const server = net.createServer();
    server.once('error', reject);
    server.listen({ port: 0, exclusive: true }, () => {
      const address = server.address();
      resolve({ server, port: Number(address?.port) });
    });
  });
}

function closeServer(server) {
  return new Promise((resolve) => {
    server.close(() => resolve());
  });
}

async function main() {
  const { server, port: occupiedPort } = await listenEphemeral();
  try {
    const freePort = await findFreePort(occupiedPort, occupiedPort + 5);
    assert.notStrictEqual(freePort, occupiedPort, 'findFreePort should skip a port already bound on all interfaces');
    console.log('\n── Port Finder Regression ──');
    console.log('PASS test-port-finder.js');
  } finally {
    await closeServer(server);
  }
}

main().catch((err) => {
  console.error(err.stack || err.message);
  process.exit(1);
});
