import type { IServiceContainer } from '@stock-bot/handlers';
import { createWebSocketHandler } from '../websocket/run-updates';
import { getLogger } from '@stock-bot/logger';

const logger = getLogger('websocket-routes');

export function createWebSocketRoute(container: IServiceContainer) {
  const wsHandler = createWebSocketHandler(container);

  // Make the handler available globally for other services
  (global as any).wsHandler = wsHandler;

  return (request: Request, server: any) => {
    const url = new URL(request.url);
    const runId = url.searchParams.get('runId');

    if (!runId) {
      return new Response('Missing runId parameter', { status: 400 });
    }

    logger.info(`WebSocket upgrade request for run: ${runId}`);

    // Upgrade the connection to WebSocket
    const success = server.upgrade(request, {
      data: { runId }
    });

    if (success) {
      logger.info(`WebSocket upgrade successful for run: ${runId}`);
      // Return undefined to indicate successful upgrade
      return;
    } else {
      logger.error(`WebSocket upgrade failed for run: ${runId}`);
      return new Response('WebSocket upgrade failed', { status: 500 });
    }
  };
}

// WebSocket connection handler for Bun
export function handleWebSocketConnection(ws: any) {
  const { runId } = ws.data;
  const wsHandler = (global as any).wsHandler;
  
  if (wsHandler && runId) {
    wsHandler.handleConnection(ws, runId);
  }
}