import { WebSocketServer, WebSocket } from 'ws';
import { createServer } from 'http';
import { randomBytes } from 'crypto';

/**
 * Test WebSocket maxPayload limit enforcement
 */

async function testMaxPayloadLimit() {
  console.log('Testing WebSocket maxPayload limit (64KB)...');

  // Create HTTP server
  const httpServer = createServer();

  // Create WebSocket server with maxPayload = 64KB
  const wss = new WebSocketServer({
    port: 0, // Use random available port
    maxPayload: 65536, // 64KB
  });

  let testPassed = false;

  wss.on('connection', (ws) => {
    console.log('✓ Client connected');

    // Send a message larger than 64KB
    const oversizedMessage = 'x'.repeat(70000); // 70KB
    
    console.log(`Attempting to send ${oversizedMessage.length} bytes...`);
    ws.send(oversizedMessage, (err) => {
      if (err) {
        console.log('✓ Error received as expected:', err.message);
        console.log('✓ maxPayload limit is correctly enforced!');
        testPassed = true;
      } else {
        console.log('✗ No error received - maxPayload NOT enforced!');
      }
    });

    ws.on('close', () => {
      httpServer.close(() => {
        wss.close(() => {
          if (testPassed) {
            console.log('\n✅ TEST PASSED: WebSocket maxPayload limit (64KB) is working correctly');
            process.exit(0);
          } else {
            console.log('\n❌ TEST FAILED: WebSocket maxPayload limit not enforced');
            process.exit(1);
          }
        });
      });
    });
  });

  httpServer.listen(0, () => {
    console.log(`WebSocket server listening on port ${httpServer.address().port}`);
  });
}

testMaxPayloadLimit().catch(console.error);
