text: const { TokenExpiredError } = require("jsonwebtoken");
  const jwt = require("jsonwebtoken");
  const config = require("../config/auth.config.js");
  const db = require("../models");
  const User = db.user;
  
  // VERIFY TOKEN
  const catchError = (err, res) => {
    if (err instanceof TokenExpiredError) {
      return res
        .status(401)
        .send({ message: "Unauthorized! Access Token was expired!" });
    }
    return res.sendStatus(401).send({ message: "Unauthorized!" });
  };
  
  verifyToken = (req, res, next) => {
    let token = req.headers["x-access-token"];
    if (!token) {
      return res.status(403).send({
        message: "No token provided!",
      });
    }
    jwt.verify(token, config.secret, (err, decoded) => {
      if (err) {
        return catchError(err, res);
      }
      req.userId = decoded.id;
      next();
    });
  };
  
  //CHECK ROLES
  isAdmin = (req, res, next) => {
    User.findByPk(req.userId).then((user) => {
      user.getRoles().then((roles) => {
        for (let i = 0; i < roles.length; i++) {
          if (roles[i].name === "admin") {
            next();
            return;
          }
        }
        res.status(403).send({
          message: "Require Admin Role!",
        });
        return;
      });
    });
  };
  isCoach = (req, res, next) => {
    User.findByPk(req.userId).then((user) => {
      user.getRoles().then((roles) => {
        for (let i = 0; i < roles.length; i++) {
          if (roles[i].name === "coach") {
            next();
            return;
          }
        }
        res.status(403).send({
          message: "Require Coach Role!",
        });
      });
    });
  };
  isCoachOrAdmin = (req, res, next) => {
    User.findByPk(req.userId).then((user) => {
      user.getRoles().then((roles) => {
        for (let i = 0; i < roles.length; i++) {
          if (roles[i].name === "coach") {
            next();
            return;
          }
          if (roles[i].name === "admin") {
            next();
            return;
          }
        }
        res.status(403).send({
          message: "Require Coach or Admin Role!",
        });
      });
    });
  };
  const authJwt = {
    verifyToken: verifyToken,
    isAdmin: isAdmin,
    isCoach: isCoach,
    isCoachOrAdmin: isCoachOrAdmin,
  };
  module.exports = authJwt;
  