import { describe, it, expect, vi, beforeEach } from 'vitest';
import { createServer } from 'node:net';

import { allocatePort } from './port-allocator.js';

describe('allocatePort', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('returns BASE_PORT (9100) when the port is available', async () => {
    const port = await allocatePort();
    expect(port).toBe(9100);
  });

  it('skips a port that is bound by another process', async () => {
    // Bind port 9100 to simulate external use
    const server = createServer();
    await new Promise<void>((resolve) => {
      server.listen(9100, '127.0.0.1', () => resolve());
    });

    try {
      const port = await allocatePort();
      expect(port).toBe(9101);
    } finally {
      await new Promise<void>((resolve) => {
        server.close(() => resolve());
      });
    }
  });
});
