
const jwt = require("jsonwebtoken");
const { cleanPath } = require("./utilities/utils");
function getToken(req) {
    var bearer = req.headers["authorization"] || null;
    var token = null;
    if (bearer) {
        bearer = bearer.split(" ")
        token = bearer[1]
    }
    return {
        token: token,
        status: bearer ? true:false
    }
}


function generateToken(params = {
    data:{},
    exp: '1d',
    config :null,
 
}) {

  
    var token = jwt.sign({
      ...params.data,

    },
        params.config.jwt_key,
        { expiresIn: '' + params.exp }
    );
    return token;

}

function verifyToken(token,config) {
 return new Promise(function(resolve, reject) {
   try{
   var decoded= jwt.verify(token, config.jwt_key)
   resolve(decoded)
   } catch(err){

    reject(err)
   }

 })

}


async function verify(token ,config) {
    
    return new Promise((resolve, reject) => {
        try {
            var decoded = jwt.verify(config.jwt_key, "shhhhh");
            resolve(decoded)
        } catch (err) {
            consola.error(err)
            reject(err)
        }
    })

}



async function authenticate(req, res, next, config) {
    const { status, token } = getToken(req)
    if(!token) return next()
     return await verify(token, config)
       .then((e) => {
         // Verify token

         return next();
       })
       .catch((err) => {
         return res.status(400).send({
           message: err,
         });
       });
}


async function loadAuth(config) {
  var Path = cleanPath(process.cwd() + "/extensions/auth/**/index.js")

  return new Promise(function (resolve, reject) {
    glob(Path, {}, function (er, files) {
      // register all endpoints
      var Auths = {};

      files.map((file) => {
        let auth = require("" + file);
        if (auth.model) {
          Auths[auth.model] = auth;
        } else {
          let authMissing = file.split("/");
          Auths[authMissing[authMissing.length - 2]] =auth;
        }
        // register({
        //   router: config.app,
        //   api: config.api,
        //  });
      });

      config.auth = {
        ...config.auth,
        ...Auths,
      };

    //  consola.success(`${Object.keys(Auths).length} Authentication controllers `);

      // files is an array of filenames.
      // If the `nonull` option is set, and nothing
      // was found, then files is ["**/*.js"]
      // er is an error object or null.
      resolve();
    });
  });
}




module.exports = {
    authenticate,
    generateToken,
    loadAuth,
    
}