/**
 * auth.js middleware — Verifica JWT e anexa user ao request
 */
const jwt = require('jsonwebtoken');

const JWT_SECRET = process.env.JWT_SECRET || 'ILVD-JWT-SECRET-MUDE-ISSO-2024';

function requireAuth(req, res, next) {
    const header = req.headers['authorization'];
    if (!header || !header.startsWith('Bearer ')) {
        return res.status(401).json({ error: 'Token não fornecido' });
    }
    const token = header.slice(7);
    try {
        const payload = jwt.verify(token, JWT_SECRET);
        req.user = payload; // { id, username, role }
        next();
    } catch (err) {
        return res.status(401).json({ error: 'Token inválido ou expirado' });
    }
}

function requireSuperAdmin(req, res, next) {
    const role = req.user?.role?.toLowerCase();
    if (!req.user || (role !== 'superadmin' && role !== 'admin')) {
        return res.status(403).json({ error: 'Acesso restrito' });
    }
    next();
}

module.exports = { requireAuth, requireSuperAdmin };
