const createApp = require('./app.js');
const config = require('./config/env.js');
const logger = require('./config/logger.js');
const { testConnection } = require('./config/database.js');
const { initRedis, closeRedis } = require('./config/redis.js');

/**
 * Start the Express server
 */
const startServer = async () => {
  // Test database connection
  const dbConnected = await testConnection();
  if (!dbConnected) {
    logger.error('Failed to connect to database. Exiting...');
    process.exit(1);
  }

  // Initialize Redis connection
  try {
    await initRedis();
    logger.info('Redis initialized successfully');
  } catch (error) {
    logger.error('Failed to initialize Redis. Exiting...', error);
    process.exit(1);
  }

  const app = createApp();

  const server = app.listen(config.port, () => {
    logger.info(`Server running in ${config.nodeEnv} mode on port ${config.port}`);
    logger.info(`Health check available at http://localhost:${config.port}/health`);
  });

  // Graceful shutdown
  const gracefulShutdown = async (signal) => {
    logger.info(`${signal} received, shutting down gracefully...`);
    
    // Close Redis connection
    try {
      await closeRedis();
    } catch (error) {
      logger.error('Error closing Redis connection:', error);
    }
    
    server.close(() => {
      logger.info('Server closed');
      process.exit(0);
    });

    // Force shutdown after 10 seconds
    setTimeout(() => {
      logger.error('Forced shutdown after timeout');
      process.exit(1);
    }, 10000);
  };

  process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
  process.on('SIGINT', () => gracefulShutdown('SIGINT'));

  return server;
};

// Start server if this file is run directly
if (require.main === module) {
  startServer();
}

module.exports = startServer;
