const mongoose = require('mongoose'); const logger = require('./logger'); let isConnected = false; const connectDB = async () => { try { // Enhanced MongoDB connection options for production stability const mongoOptions = { maxPoolSize: 10, serverSelectionTimeoutMS: 5000, socketTimeoutMS: 45000, bufferMaxEntries: 0, bufferCommands: false, autoIndex: process.env.NODE_ENV !== 'production', maxIdleTimeMS: 30000, minPoolSize: 2, retryWrites: true, retryReads: true }; const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/uga-chatbot'; logger.info('Attempting to connect to MongoDB...'); const conn = await mongoose.connect(mongoUri, mongoOptions); logger.info(`MongoDB Connected Successfully: ${conn.connection.host}`); isConnected = true; // Connection event listeners mongoose.connection.on('error', (err) => { logger.error('MongoDB connection error:', err); }); mongoose.connection.on('disconnected', () => { logger.warn('MongoDB disconnected'); isConnected = false; }); mongoose.connection.on('reconnected', () => { logger.info('MongoDB reconnected'); isConnected = true; }); // Enhanced connection event listeners mongoose.connection.on('connecting', () => { logger.info('MongoDB attempting to reconnect...'); }); mongoose.connection.on('connected', () => { logger.info('MongoDB connected'); isConnected = true; }); // Create indexes if needed if (process.env.NODE_ENV !== 'production') { await ensureIndexes(); } } catch (error) { logger.error('Error connecting to MongoDB:', error.message); logger.warn('MongoDB unavailable - running without persistent storage'); // Don't exit process for MongoDB connection failure in production // This allows the app to run with local AI only if (process.env.NODE_ENV !== 'production') { process.exit(1); } } }; // Ensure database indexes are created const ensureIndexes = async () => { try { // Import models to ensure indexes are created require('../models/User'); require('../models/UGAEvent'); // Check if ChatHistory model exists const fs = require('fs'); const path = require('path'); const chatHistoryPath = path.join(__dirname, '../models/ChatHistory.js'); if (fs.existsSync(chatHistoryPath)) { require('../models/ChatHistory'); } else { // Import from root models directory const rootChatHistoryPath = path.join(__dirname, '../../../models/ChatHistory.js'); if (fs.existsSync(rootChatHistoryPath)) { require('../../../models/ChatHistory'); } } logger.info('Database indexes ensured'); } catch (error) { logger.warn('Could not ensure indexes:', error.message); } }; // Helper function to check if database is available const isDatabaseConnected = () => isConnected && mongoose.connection.readyState === 1; // Graceful shutdown handler const gracefulShutdown = async () => { if (mongoose.connection.readyState !== 0) { try { await mongoose.connection.close(); logger.info('MongoDB connection closed through app termination'); } catch (error) { logger.error('Error closing MongoDB connection:', error.message); } } isConnected = false; }; // Setup graceful shutdown handlers process.on('SIGINT', gracefulShutdown); process.on('SIGTERM', gracefulShutdown); process.on('SIGUSR2', gracefulShutdown); // Nodemon restart module.exports = { connectDB, isDatabaseConnected, gracefulShutdown, ensureIndexes };