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

module.exports = function wechatHeadersAuth(req, res, next) {
    requireWechatOpenid(req, res, (openidError) => {
        if (openidError) {
            return next(openidError)
        }

        const usersWxOpenid = req.usersWxOpenid
        const authHeader = req.headers.authorization || ''
        const [scheme, token] = authHeader.split(' ')

        if (scheme !== 'Bearer' || !token) {
            return next(new AppError('请求头缺少 Authorization', 401))
        }

        try {
            const decoded = jwt.verify(token, env.jwtSecret)
            if (decoded.users_wx_openid && decoded.users_wx_openid !== usersWxOpenid) {
                return next(new AppError('请求头中的 users_wx_openid 与令牌不匹配', 401))
            }
            req.user = decoded
            next()
        } catch {
            next(new AppError('认证令牌无效或已过期', 401))
        }
    })
}
