const jwt = require('../tools/jwt');
const { validateSession } = require('../core/auth.core');

const userAuth = async (req, res, next) => {
    const token = (req.cookies && req.cookies.auth_token) || jwt.getToken(req.headers['authorization']);

    const unauthorized = (reason) => {
        if (req.accepts('html')) {
            const redirect = encodeURIComponent(req.originalUrl);
            return res.redirect(`/login?redirect=${redirect}`);
        }
        return res.status(401).json({ error: reason || 'Non autorizzato' });
    };

    if (!token || typeof token !== 'string' || token.length > 2048) {
        return unauthorized('Token mancante o non valido');
    }

    const verified = jwt.verifyToken(token);
    if (!verified.valid) {
        return unauthorized(`Sessione non valida (${verified.reason})`);
    }

    try {
        await validateSession(verified.payload.session_id);
    } catch (err) {
        return unauthorized('Sessione non valida o revocata');
    }

    req.user = verified.payload;
    next();
};

module.exports = userAuth;
