const jwt = require("jsonwebtoken");
const User = require("../../models").users;
// const GetSession = require("../../models").sessions;
const auth = async (req, res, next) => {
  try {
    const sessionToken = req?.session?.data?.token;
    console.log("sessionToken", sessionToken);
    if (!sessionToken) {
      return res.redirect("/staff-login");
    }
    // const token = req.header('Authorization').replace('Bearer ', '')
    const token = sessionToken;
    var decoded = jwt.verify(token, process.env.JWT_pa);

    if (!token) {
      return res.redirect("/staff-login");
    }

    let authUser = await User.findOne({
      where: {
        username: decoded.username,
        remember_token: token,
      },
      attributes: [
        "id",
        "password",
        "username",
        "first_login",
        "firstname",
        "lastname",
        "second_role",
        "role",
      ],
      raw: true,
    });
    // const sessions = await GetSession.findAll();
    if (authUser) {
      req.token = token;
      req.user = authUser;
      req.department_id = authUser.department_id;
      req.type = "staff";
      // req.session = sessions;
      next();
    } else {
      console.log(authUser);
      return res.redirect("/staff-login");
    }
  } catch (e) {
    console.log(e);
    if (e == "JsonWebTokenError: invalid token") {
      return res.redirect("/staff-login");
    }

    return res.redirect("/staff-login");
  }
};

module.exports = auth;
