/**
 * Routes creation with improved DI pattern
 */

import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { exchangeRoutes } from './exchange.routes';
import { healthRoutes } from './health.routes';
import { createQueueRoutes } from './queue.routes';

/**
 * Creates all routes with access to type-safe services
 */
export function createRoutes(services: IServiceContainer): Hono {
  const app = new Hono();

  // Mount routes that don't need services
  app.route('/health', healthRoutes);

  // Mount routes that need services
  app.route('/api/exchanges', exchangeRoutes);
  app.route('/api/queue', createQueueRoutes(services));

  // Store services in app context for handlers that need it
  app.use('*', async (c, next) => {
    c.set('services', services);
    await next();
  });

  // Add a new endpoint to test the improved DI
  app.get('/api/di-test', async c => {
    try {
      const services = c.get('services') as IServiceContainer;

      // Test MongoDB connection
      const mongoStats = services.mongodb?.getPoolMetrics?.() || {
        status: services.mongodb ? 'connected' : 'disabled',
      };

      // Test PostgreSQL connection
      const pgConnected = services.postgres?.connected || false;

      // Test cache
      const cacheReady = services.cache?.isReady() || false;

      // Test queue
      const queueStats = services.queue?.getGlobalStats() || { status: 'disabled' };

      return c.json({
        success: true,
        message: 'Improved DI pattern is working!',
        services: {
          mongodb: mongoStats,
          postgres: { connected: pgConnected },
          cache: { ready: cacheReady },
          queue: queueStats,
        },
        timestamp: new Date().toISOString(),
      });
    } catch (error) {
      const services = c.get('services') as IServiceContainer;
      services.logger.error('DI test endpoint failed', { error });
      return c.json(
        {
          success: false,
          error: error instanceof Error ? error.message : String(error),
        },
        500
      );
    }
  });

  return app;
}
