const jwt = require('jsonwebtoken')
const env = require('../config/env')
const AppError = require('../utils/appError')

module.exports = function jwtAuth(req, res, next) {
    const authHeader = req.headers.authorization || ''
    const [scheme, token] = authHeader.split(' ')

    if (scheme !== 'Bearer' || !token) {
        return next(new AppError('未提供有效的认证令牌', 401))
    }

    try {
        const decoded = jwt.verify(token, env.jwtSecret)
        req.user = decoded
        next()
    } catch {
        next(new AppError('认证令牌无效或已过期', 401))
    }
}
