import { createServer } from 'http';
import { app, logger } from './app';
import { config } from './config';
import { connectRedis } from './config/redis';
import { initializeSocket } from './socket';
import { loadLuaScripts } from './services/vote.service';
import { loadVotingScripts } from './services/voting.engine';

async function main(): Promise<void> {
  try {
    // Connect to Redis
    logger.info('Connecting to Redis...');
    await connectRedis();

    // Load Lua scripts
    logger.info('Loading Lua scripts...');
    await loadLuaScripts();
    await loadVotingScripts();

    // Create HTTP server
    const httpServer = createServer(app);

    // Initialize Socket.io
    logger.info('Initializing Socket.io...');
    await initializeSocket(httpServer);

    // Start server
    httpServer.listen(config.port, () => {
      logger.info({ port: config.port, env: config.nodeEnv }, 'Server started');
      logger.info(`Health check: http://localhost:${config.port}/health`);
    });

    // Graceful shutdown
    const shutdown = async (signal: string) => {
      logger.info({ signal }, 'Shutdown signal received');

      httpServer.close(() => {
        logger.info('HTTP server closed');
        process.exit(0);
      });

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

    process.on('SIGTERM', () => shutdown('SIGTERM'));
    process.on('SIGINT', () => shutdown('SIGINT'));
  } catch (error) {
    logger.error({ error }, 'Failed to start server');
    process.exit(1);
  }
}

main();
