// npx ts-node test-twilio-client.ts
import WebSocket from 'ws';

// URL of your NestJS WebSocket gateway
const WS_URL = 'ws://localhost:3000/ws'; // change port if different

const ws = new WebSocket(WS_URL);

ws.on('open', () => {
  console.log('✅ Connected to TwilioGateway');

  // Generate dummy callSid (chatId)
  const callSid = 'CA1234567890abcdef';
  const streamSid = 'IE_TEST_STREAM_123';

  // 1️⃣ Send "connected" event
  ws.send(JSON.stringify({ event: 'connected' }));

  // 2️⃣ Send "start" event with callSid and streamSid
  ws.send(JSON.stringify({
    event: 'start',
    start: {
      callSid,
      streamSid,
    },
  }));

  // 3️⃣ Send a few dummy "media" events (simulate audio chunks)
  const dummyAudioChunks = ['Hello', 'This is a test', 'Streaming audio!'];

  dummyAudioChunks.forEach((chunk, index) => {
    setTimeout(() => {
      const payload = Buffer.from(chunk).toString('base64');
      ws.send(JSON.stringify({
        event: 'media',
        media: { payload },
        streamSid,
      }));
    }, index * 500); // stagger chunks by 500ms
  });

  // 4️⃣ After all media chunks, send "stop"
  setTimeout(() => {
    ws.send(JSON.stringify({ event: 'stop', streamSid }));
  }, dummyAudioChunks.length * 500 + 500);
});

ws.on('message', (msg: string) => {
  console.log('📥 Received:', msg);
});

ws.on('close', () => {
  console.log('❌ Connection closed');
});

ws.on('error', (err) => {
  console.error('⚠️ Error:', err);
});
