const { models, sequelize } = require('../models')
const jwt = require('jsonwebtoken')
const ResponseHandle = require('../utils/responseHandle')

const verifyAccessToken = async (req, res, next) => {
  if (process.env.API_GUARD === 'true') {
    const authHeader = req.headers.authorization

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return ResponseHandle.error(res, 400, 'Access token is required')
    }

    const token = authHeader.split(' ')[1]

    try {
      const decoded = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET)
      req.user = decoded
      next()
    } catch (error) {
      return ResponseHandle.error(res, 401, 'Invalid access token')
    }
  } else {
    next()
  }
}

module.exports = { verifyAccessToken }
