import { createServer } from 'node:net'

function canListen(host: string, port: number): Promise<boolean> {
  return new Promise(resolve => {
    const server = createServer()

    server.once('error', () => resolve(false))
    server.once('listening', () => server.close(() => resolve(true)))
    server.listen({ host, port, exclusive: true })
  })
}

export async function findAvailablePort(host: string, startPort: number): Promise<number> {
  for (let port = startPort; port <= 65535; port += 1) {
    if (await canListen(host, port)) return port
  }

  throw new Error(`未找到可用端口（起始端口：${startPort}）`)
}
