/**
 * Server Entry Point
 * Main file that starts the Express server
 */

// Load environment variables from .env file
require('dotenv').config();

// Import Express application
const app = require('./app');
// Import app configuration
const appConfig = require('./config/app');
// Import logger utility
const logger = require('./utils/logger');
// Import database connection
const db = require('./models');

/**
 * Start server function
 * Initializes database connection and starts Express server
 */
const startServer = async () => {
  try {
    // Database connection (required - server cannot start without database)
    await db.sequelize.authenticate();
    logger.info('Database connection established successfully.');
    
    // Sync database models (use with caution in production)
    if (process.env.NODE_ENV === 'development') {
      // Use force: true to drop and recreate tables (DEVELOPMENT ONLY)
      // This avoids MySQL index limit issues with alter: true
      // WARNING: This will delete all data in the database!
      const syncOption = process.env.DB_FORCE_SYNC === 'false' ? { force: false } : { alter: false };
      
      try {
        await db.sequelize.sync({alter: false , force: false});
        logger.info('Database models synchronized.');
        if (syncOption.force) {
          logger.warn('⚠️  Database was recreated (all data lost)');
        }
      } catch (syncError) {
        // If alter fails with index limit error, suggest using force sync
        if (syncError.name === 'SequelizeDatabaseError' && syncError.message.includes('Too many keys')) {
          logger.error('❌ Database sync failed: Too many indexes. Use DB_FORCE_SYNC=true to recreate database.');
          logger.error('   Set DB_FORCE_SYNC=true in .env and restart server (WARNING: Deletes all data)');
          throw syncError;
        }
        throw syncError;
      }
    }

    // Start Express server
    const server = app.listen(appConfig.server.port, appConfig.server.host, () => {
      // Log server start information
      logger.info(`Server running on http://${appConfig.server.host}:${appConfig.server.port}`);
      logger.info(`Environment: ${appConfig.server.env}`); // Log current environment
    });

    // Graceful shutdown handler - Handle SIGTERM signal
    process.on('SIGTERM', () => {
      logger.info('SIGTERM signal received: closing HTTP server');
      server.close(() => {
        logger.info('HTTP server closed');
        // Close database connection gracefully
        db.sequelize.close().then(() => {
          logger.info('Database connection closed.');
        });
      });
    });

    // Graceful shutdown handler - Handle SIGINT signal (Ctrl+C)
    process.on('SIGINT', () => {
      logger.info('SIGINT signal received: closing HTTP server');
      server.close(() => {
        logger.info('HTTP server closed');
        // Close database connection gracefully
        // db.sequelize.close().then(() => {
        //   logger.info('Database connection closed.');
        // });
        process.exit(0); // Exit process
      });
    });

    // Handle unhandled promise rejections
    process.on('unhandledRejection', (err) => {
      logger.error('Unhandled Promise Rejection:', err);
      // Close server and exit process
      server.close(() => {
        process.exit(1); // Exit with error code
      });
    });

    // Handle uncaught exceptions
    process.on('uncaughtException', (err) => {
      logger.error('Uncaught Exception:', err);
      process.exit(1); // Exit with error code
    });

  } catch (error) {
    // Log error and exit if server fails to start
    logger.error('Failed to start server:', error);
    process.exit(1); // Exit with error code
  }
};

// Start the server
startServer();

