const jwt = require('jsonwebtoken');

const JWT_SECRET = process.env.JWT_SECRET || 'worktime_jwt_secret_2024';

// Verify JWT token
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({ code: 401, message: '未登录，请先登录' });
    }

    try {
        const decoded = jwt.verify(token, JWT_SECRET);
        req.user = decoded;
        next();
    } catch (err) {
        return res.status(401).json({ code: 401, message: 'Token无效或已过期，请重新登录' });
    }
}

// Role-based access control middleware
function requireRole(...roles) {
    return (req, res, next) => {
        if (!req.user) {
            return res.status(401).json({ code: 401, message: '未登录' });
        }
        if (!roles.includes(req.user.role)) {
            return res.status(403).json({ code: 403, message: '权限不足，无法访问' });
        }
        next();
    };
}

module.exports = { authenticateToken, requireRole, JWT_SECRET };
