function requireTrinityAccess(req, res, next) {
    // Allow localhost requests (for curl debugging from Command Center)
    const ip = req.ip || req.connection.remoteAddress;
    if (ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1') {
        res.locals.adminUser = { username: 'localhost', id: 'localhost' };
        res.locals.currentPath = req.path;
        return next();
    }
    
    if (!req.isAuthenticated()) {
        return res.redirect('/auth/discord');
    }
    
    const admins = (process.env.ADMIN_USERS || '').split(',');
    if (!admins.includes(req.user.id)) {
        return res.status(403).send('Forbidden: Trinity Access Only.');
    }
    
    // Inject user and current path into all EJS views
    res.locals.adminUser = req.user;
    res.locals.currentPath = req.path;
    next();
}

module.exports = { requireTrinityAccess };
