const jwt = require("jsonwebtoken");
const User = require("../../models").users;
const Profile = require("../../models").profiles;
const UserRole = require("../../models").user_roles;
const Sessions = require("../../models").sessions;

const auth = async (req, res, next) => {
  try {
    const sessionToken = req.session.data.token;
    if (!sessionToken) {
      return res.render("login/staff.ejs", {
        error: {
          statusCode: "401",
          success: false,
          message: "Error",
          error: "Login to access the staff dashbaord",
        },
        success: {
          statusCode: "200",
          success: false,
          message: undefined,
        },
      });
    }
    // 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,
      },
      include: [{ model: UserRole }],
    });

    const authProfile = await Profile.findOne({
      where: {
        user_id: authUser.id,
      },
    });

    let userDept = await Profile.findOne({ where: { user_id: authUser.id } });
    authUser = JSON.parse(JSON.stringify(authUser));
    const allSessions = await Sessions.findAll({raw:true})
    if (authUser) {
      req.token = token;
      req.user = authUser;
      req.profile = authProfile;
      req.department_id = userDept.department_id;
      req.type = "staff";
      req.sessions = allSessions
      next();
    } else {
      return res.redirect("/staff-login");
    }
  } catch (e) {
    if (e == "JsonWebTokenError: invalid token") {
      return res.redirect("/staff-login");
    }
    return res.redirect("/staff-login");
  }
};

module.exports = auth;
