/**
 * Stock Bot Web API
 * Simplified entry point using ServiceApplication framework
 */

import { ServiceApplication } from '@stock-bot/di';
import { getLogger } from '@stock-bot/logger';
import { initializeStockConfig } from '@stock-bot/stock-config';
// Local imports
import { createRoutes } from './routes/create-routes';

// Initialize configuration with service-specific overrides
const config = initializeStockConfig('webApi');

// Override queue settings for web-api (no workers needed)
if (config.queue) {
  config.queue.workers = 0;
  config.queue.concurrency = 0;
  config.queue.enableScheduledJobs = false;
}

// Log the full configuration
const logger = getLogger('web-api');
logger.info('Service configuration:', config);

// Create service application
const app = new ServiceApplication(
  config,
  {
    serviceName: 'web-api',
    enableHandlers: false, // Web API doesn't use handlers
    enableScheduledJobs: false, // Web API doesn't use scheduled jobs
    corsConfig: {
      origin: ['http://localhost:4200', 'http://localhost:3000', 'http://localhost:3002', 'http://localhost:5173', 'http://localhost:5174'],
      allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
      allowHeaders: ['Content-Type', 'Authorization'],
      credentials: true,
    },
    serviceMetadata: {
      version: '1.0.0',
      description: 'Stock Bot REST API',
      endpoints: {
        health: '/health',
        exchanges: '/api/exchanges',
      },
    },
  },
  {
    // Custom lifecycle hooks
    onStarted: _port => {
      const logger = getLogger('web-api');
      logger.info('Web API service startup initiated with ServiceApplication framework');
    },
  }
);

// Container factory function
async function createContainer(config: any) {
  const { ServiceContainerBuilder } = await import('@stock-bot/di');

  const container = await new ServiceContainerBuilder()
    .withConfig(config)
    .withOptions({
      enableQuestDB: false, // Disable QuestDB for now
      enableMongoDB: true,
      enablePostgres: true,
      enableCache: true,
      enableQueue: true, // Enable for pipeline operations
      enableBrowser: false, // Web API doesn't need browser
      enableProxy: false, // Web API doesn't need proxy
    })
    .build(); // This automatically initializes services

  return container;
}

// Start the service
app.start(createContainer, createRoutes).catch(error => {
  const logger = getLogger('web-api');
  logger.fatal('Failed to start web API service', { error });
  process.exit(1);
});
