const jwt = require('jsonwebtoken');

const verifyAdmin = (req, res, next) => {
    // Gufata token ituruka mu mutwe wa request headers (Authorization)
    const token = req.headers['authorization']?.split(' ')[1];

    if (!token) {
        return res.status(403).json({ message: 'Access denied. No token provided.' });
    }

    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET || 'fallback_secret');
        req.user = decoded;

        // CONDITION: Niba uyu mukozi atari Admin, ihita imubora (Forbidden)
        if (req.user.role !== 'Admin') {
            return res.status(403).json({ message: 'Forbidden! Only Administrators can perform this action.' });
        }

        next(); // Komeza niba ari Admin nyiri izina
    } catch (err) {
        return res.status(401).json({ message: 'Invalid or expired token.' });
    }
};

module.exports = { verifyAdmin };
