const jwt = require('jsonwebtoken');
const JWT_CONFIG = require('../config/jwt');

/**
 * Middleware to verify JWT token and attach user to request
 */
function authenticateToken(req, res, next) {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

    if (!token) {
        return res.status(401).json({
            status: 'error',
            message: 'Access token required'
        });
    }

    try {
        const decoded = jwt.verify(token, JWT_CONFIG.secret);
        req.user = decoded; // { id, username, email, role, roleId }
        next();
    } catch (error) {
        if (error.name === 'TokenExpiredError') {
            return res.status(401).json({
                status: 'error',
                message: 'Token expired'
            });
        }
        return res.status(403).json({
            status: 'error',
            message: 'Invalid token'
        });
    }
}

/**
 * Optional authentication - doesn't fail if no token provided
 * But validates token if present
 */
function optionalAuth(req, res, next) {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
        req.user = null;
        return next();
    }

    try {
        const decoded = jwt.verify(token, JWT_CONFIG.secret);
        req.user = decoded;
        next();
    } catch (error) {
        req.user = null;
        next();
    }
}

module.exports = {
    authenticateToken,
    optionalAuth
};
