const { getUnreadMessageCount, isAdminInDb } = require('../database');

// Check if user is authenticated
function requireAuth(req, res, next) {
    if (!req.session.authenticated) {
        req.flash('Please login to access this page', 'warning');
        return res.redirect('/');
    }
    next();
}

// Check if user is admin
function requireAdmin(req, res, next) {
    if (!req.session.authenticated) {
        req.flash('Please login to access the admin panel', 'warning');
        return res.redirect('/');
    }

    const userEmail = req.session.user_email;
    if (!userEmail || !req.session.is_admin || !isAdminInDb(userEmail)) {
        req.session.authenticated = false;
        req.session.is_admin = false;
        req.flash('Admin access required', 'danger');
        return res.redirect('/');
    }
    next();
}

// Inject unread message count to all views
function injectUnreadCount(req, res, next) {
    res.locals.unread_count = 0;

    if (req.session.authenticated && req.session.user_email) {
        res.locals.unread_count = getUnreadMessageCount(req.session.user_email);
    }

    next();
}

module.exports = {
    requireAuth,
    requireAdmin,
    injectUnreadCount
};
