/**
 * Data Pipeline Service
 * 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';
import { createRoutes } from './routes/create-routes';
import { setupServiceContainer } from './container-setup';
// Local imports
import { initializeAllHandlers } from './handlers';

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

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

// Create service application
const app = new ServiceApplication(
  config,
  {
    serviceName: 'data-pipeline',
    enableHandlers: true,
    enableScheduledJobs: true,
    corsConfig: {
      origin: '*',
      allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
      allowHeaders: ['Content-Type', 'Authorization'],
      credentials: false,
    },
    serviceMetadata: {
      version: '1.0.0',
      description: 'Data processing and transformation pipeline',
      endpoints: {
        health: '/health',
        operations: '/api/operations',
      },
    },
  },
  {
    // Custom lifecycle hooks
    onContainerReady: container => {
      // Setup service-specific configuration
      const enhancedContainer = setupServiceContainer(config, container);
      return enhancedContainer;
    },
    onStarted: _port => {
      const logger = getLogger('data-pipeline');
      logger.info('Data pipeline service startup initiated with ServiceApplication framework');
    },
  }
);

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

  const container = await builder
    .withConfig(config)
    .withOptions({
      enableQuestDB: false, // Disabled for now due to auth issues
      // Data pipeline needs all databases
      enableMongoDB: true,
      enablePostgres: true,
      enableCache: true,
      enableQueue: true,
      enableBrowser: false, // Data pipeline doesn't need browser
      enableProxy: false, // Data pipeline doesn't need proxy
      skipInitialization: false, // Let builder handle initialization
    })
    .build();

  return container;
}

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