const logger = require('../utils/logger');

const requireAuth = (req, res, next) => {
    // Check for both authentication patterns used in your app
    const isAuthenticated = (req.session && req.session.authenticated) || 
                           (req.session && req.session.userId && req.session.userEmail);
    
    if (isAuthenticated) {
        next();
    } else {
        logger.warn('Unauthorized access attempt', {
            ip: req.ip,
            path: req.path,
            userAgent: req.get('User-Agent')
        });
        
        if (req.xhr || req.headers.accept?.indexOf('json') > -1) {
            res.status(401).json({ 
                success: false, 
                error: 'Authentication required' 
            });
        } else {
            res.redirect('/login.html');
        }
    }
};

const requireAdmin = (req, res, next) => {
    // Check for both authentication patterns used in your app
    const isAuthenticated = (req.session && req.session.authenticated) || 
                           (req.session && req.session.userId && req.session.userEmail);
    
    if (isAuthenticated && req.session.isAdmin) {
        next();
    } else {
        logger.warn('Unauthorized admin access attempt', {
            ip: req.ip,
            path: req.path,
            user: req.session?.userEmail || 'anonymous',
            userAgent: req.get('User-Agent')
        });
        
        if (req.xhr || req.headers.accept?.indexOf('json') > -1) {
            res.status(403).json({ 
                success: false, 
                error: 'Admin access required' 
            });
        } else {
            res.redirect('/login.html');
        }
    }
};

module.exports = {
    requireAuth,
    requireAdmin
};