require('dotenv').config(); const express = require('express'); const path = require('path'); const database = require('./config/database'); const routes = require('./routes'); const app = express(); const PORT = process.env.PORT || 3000; app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, '../views')); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(express.static(path.join(__dirname, '../public'))); app.use('/', routes); app.use((req, res) => { res.status(404).render('error', { message: 'Page not found', error: { status: 404 } }); }); app.use((err, req, res, next) => { console.error(err.stack); res.status(500).render('error', { message: 'Something went wrong!', error: process.env.NODE_ENV === 'development' ? err : {} }); }); async function startServer() { try { await database.connect(); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); }); } catch (error) { console.error('Failed to start server:', error); process.exit(1); } } process.on('SIGINT', async () => { console.log('\nShutting down gracefully...'); await database.close(); process.exit(0); }); process.on('SIGTERM', async () => { console.log('\nShutting down gracefully...'); await database.close(); process.exit(0); }); startServer();