const settingsDB = require('./settings-db');
const path = require('path');

/**
 * Middleware to check if maintenance mode is enabled
 * Redirects non-admin users to maintenance page
 */
const checkMaintenanceMode = (req, res, next) => {
    // Skip for admin routes, API routes, and static assets
    // We want to allow /admin login so admins can turn off maintenance mode
    if (req.path.startsWith('/admin') || 
        req.path.startsWith('/api') || 
        req.path.match(/\.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$/)) {
        return next();
    }

    const maintenanceMode = settingsDB.get('maintenance_mode');
    
    if (maintenanceMode === 'true') {
        // Check if user is authenticated as admin (bypass maintenance)
        // We need to ensure session middleware is running before this
        if (req.session && req.session.authenticated) {
            return next();
        }
        
        // Get maintenance settings
        const message = settingsDB.get('maintenance_message');
        const eta = settingsDB.get('maintenance_eta');
        
        // Render maintenance page with settings
        return res.status(503).render('maintenance', { 
            message: message || '',
            eta: eta || null
        });
    }
    
    next();
};

module.exports = {
    checkMaintenanceMode
};
