import * as http from 'http';
import { WebSocketServer, WebSocket } from 'ws';
import { IVoiceEngine } from '../types';
import { handleTwilioCall } from './bridge';

export class TwilioRealtimeEngine implements IVoiceEngine {
  attach(server: http.Server): void {
    const wss = new WebSocketServer({ noServer: true });

    server.on('upgrade', (request, socket, head) => {
      const url = new URL(request.url || '/', `http://${request.headers.host}`);

      if (!url.pathname.startsWith('/stream/')) {
        return;
      }

      let sessionId: string;
      try {
        sessionId = decodeURIComponent(url.pathname.slice('/stream/'.length));
      } catch {
        console.warn('[Engine/Twilio] Malformed session ID encoding in path — rejecting');
        socket.destroy();
        return;
      }
      if (!sessionId) {
        console.warn('[Engine/Twilio] Upgrade request missing session ID in path — rejecting');
        socket.destroy();
        return;
      }

      wss.handleUpgrade(request, socket, head, (ws: WebSocket) => {
        wss.emit('connection', ws, request);
        handleTwilioCall(ws, sessionId).catch((err) => {
          console.error('[Engine/Twilio] Unhandled error in handleTwilioCall:', err);
          ws.close();
        });
      });
    });

    console.log('[Engine/Twilio] TwilioRealtimeEngine attached — listening for /stream upgrades');
  }
}
