const { WebSocketServer, WebSocket } = require('ws');
const { createServer } = require('http');

const httpServer = createServer();
const wss = new WebSocketServer({
  port: 0,
  maxPayload: 65536, // 64KB
});

let testPassed = false;

wss.on('connection', (ws) => {
  console.log('Client connected');
  
  // Send oversized message
  const oversized = 'x'.repeat(70000);
  console.log('Sending 70KB message...');
  
  ws.send(oversized, (err) => {
    if (err) {
      console.log('✓ Error received (expected):', err.message);
      testPassed = true;
    } else {
      console.log('✗ No error - maxPayload NOT enforced!');
    }
    
    ws.close();
    httpServer.close();
    wss.close();
    
    if (testPassed) {
      console.log('✅ TEST PASSED: maxPayload (64KB) is enforced');
      process.exit(0);
    } else {
      console.log('❌ TEST FAILED');
      process.exit(1);
    }
  });
});

httpServer.listen(0, () => {
  const port = httpServer.address().port;
  console.log('Server listening on port', port);
  
  // Create client immediately
  const ws = new WebSocket(`ws://localhost:${port}`);
  
  ws.on('open', () => {
    console.log('Client connected to server');
  });
  
  ws.on('error', (err) => {
    console.log('Client error:', err.message);
    httpServer.close();
    wss.close();
  });
  
  ws.on('close', () => {
    if (!testPassed) {
      console.log('❌ Test timed out - no response received');
      process.exit(1);
    }
  });
});

// Timeout after 5 seconds
setTimeout(() => {
  console.log('❌ Test timed out');
  process.exit(1);
}, 5000);

// Create client immediately
const ws = new WebSocket(`ws://localhost:${port}`);
