const { verifyToken } = require('../config/jwt');
const TokenBlacklist = require('../models/TokenBlacklist');

// Authentication middleware to verify JWT token
const authenticateToken = (req, res, next) => {
    // Get token from Authorization header
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

    if (!token) {
        return res.status(401).json({ 
            error: 'Access denied. No token provided.',
            message: 'Please provide a Bearer token in the Authorization header.'
        });
    }

    // Check blacklist then verify token
    TokenBlacklist.isBlacklisted(token, (err, blacklisted) => {
        if (err) {
            return res.status(500).json({ error: 'Failed to validate token', message: err.message });
        }
        if (blacklisted) {
            return res.status(401).json({ 
                error: 'Token has been invalidated.',
                message: 'Please login again to get a new token.'
            });
        }

        const decoded = verifyToken(token);
        if (!decoded) {
            return res.status(403).json({ 
                error: 'Invalid or expired token.',
                message: 'Please login again to get a new token.'
            });
        }

        // Attach user info and raw token to request object
        req.user = decoded;
        req.token = token;
        next();
    });
};

module.exports = authenticateToken;

