const jwt = require('jsonwebtoken');
const Admin = require('./models/admin/Admin')


const config = {
   // secret for generating jwt token
   secretKey: 'b8a537eefc8e8e938509bd6a557e51d8f9459842691b013254fb8f31e6d6c78713f65fad589f0b036481907b7014e249d28da1ea359f8a5b7f59da3aa5b0455f'
}

module.exports = config

// check if admin logged in
module.exports.isAdmin = function (req, res, next) {
   const token = req.headers.authorization
   if (token) {
      // check if token is not destroyed
      Admin.findOne({token: token}, (err, user) => {
         if (err) throw err
         if (user) {
            // verifies secret and checks if the token is expired
            jwt.verify(user.token.replace(/^Bearer\s/, ''), config.secretKey, (err, decoded) => {
               if (err) {
                  return res.status(401).json({message: 'unauthorized'})
               } else {
                  return next()
               }
            })
         } else return res.status(401).json({message: 'unauthorized'})
      })
   } else {
      return res.status(401).json({message: 'unauthorized'})
   }
}
