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

const userAuth = async (req, res, next) => {
    console.log('[DEBUG MIDDLEWARE] userAuth() START - path:', req.path);
    
    const token = (req.cookies && req.cookies.auth_token) || jwt.getToken(req.headers['authorization']);
    console.log('[DEBUG MIDDLEWARE] token found:', !!token);

    const redirectToLogin = () => {
        console.log('[DEBUG MIDDLEWARE] redirectToLogin()');
        if (req.accepts('html')) {
            const redirect = encodeURIComponent(req.originalUrl);
            return res.redirect(`/login?redirect=${redirect}`);
        }
        return res.status(401).json({ error: 'Accesso negato: token mancante' });
    };

    if (!token || typeof token !== 'string') {
        console.log('[DEBUG MIDDLEWARE] no token or invalid type');
        return redirectToLogin();
    }

    if (token.length > 2048) {
        console.log('[DEBUG MIDDLEWARE] token too long');
        return redirectToLogin();
    }

    const verified = jwt.verifyToken(token);
    console.log('[DEBUG MIDDLEWARE] jwt.verifyToken() result - valid:', verified.valid);
    
    if (!verified.valid) {
        console.log('[DEBUG MIDDLEWARE] token not valid - reason:', verified.reason);
        if (req.accepts('html')) {
            return res.redirect('/login');
        }
        return res.status(401).json({
            error: 'Sessione non valida o scaduta',
            reason: verified.reason
        });
    }

    try {
        console.log('[DEBUG MIDDLEWARE] calling validateSession() with session_id:', verified.payload.session_id);
        await validateSession(verified.payload.session_id);
        console.log('[DEBUG MIDDLEWARE] validateSession() SUCCESS');
    } catch (err) {
        console.error('[DEBUG MIDDLEWARE] validateSession() FAILED:', err.message);
        if (req.accepts('html')) {
            return res.redirect('/login');
        }
        return res.status(401).json({ error: 'Sessione non valida o revocata' });
    }

    req.user = verified.payload;
    console.log('[DEBUG MIDDLEWARE] auth SUCCESS - user_id:', req.user.user_id);
    next();
};

module.exports = userAuth;
