const app = require('./app');
const config = require('./config');
const db = require('./models');

const PORT = config.port;

// Test database connection and sync models
db.sequelize.authenticate()
  .then(() => {
    console.log('Database connection has been established successfully.');
    
    // In development, you might want to sync models
    // In production, use migrations only
    if (config.env === 'development') {
      // db.sequelize.sync({ alter: true }); // Use migrations instead
    }
    
    app.listen(PORT, '0.0.0.0', () => {
      console.log(`Server is running on port ${PORT} in ${config.env} mode`);
      console.log(`API endpoint: http://localhost:${PORT}${config.api.prefix}/${config.api.version}`);
      console.log(`Network access: http://<your-ip>:${PORT}${config.api.prefix}/${config.api.version}`);
    });
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
    process.exit(1);
  });

// Graceful shutdown
process.on('SIGTERM', () => {
  console.log('SIGTERM signal received: closing HTTP server');
  db.sequelize.close();
  process.exit(0);
});

process.on('SIGINT', () => {
  console.log('SIGINT signal received: closing HTTP server');
  db.sequelize.close();
  process.exit(0);
});

