// library useful for development
const passport = require("passport");
const jwt = require("jsonwebtoken");

// function to handle the login process
const casLogin = function (req, res, next) {
  console.log("Beginning log in....");

  // hard-coded for now.
  const JWT_SECRET = "secret_key";

  // call the authenticate function with CAS
  passport.authenticate("cas", function (err, user, info) {
    if (err) {
      console.log("found error during authentication: ", err);
      return next(err);
    }

    // return 401 if user not found
    if (!user) {
      console.log("User not found: ", user);
      return res.status(401).json({ message: "Authentication failed." });
    }

    console.log("Found user");

    // create a user object and redirect user
    // to the root route
    req.logIn(user, function (err) {
      console.log("Executing log in.");
      if (err) {
        return next(err);
      }

      // payload for the JWT token
      const payload = {
        id: user.id,
        role: user.permissionLevel || "guest",
        username: user.username,
      };

      // sign the token with secret key
      const token = jwt.sign(payload, JWT_SECRET, { expiresIn: "1h" });

      // Send the JWT token to the frontend
      console.log("sending JWT To: ", process.env.FRONTEND_URL);
      res.redirect(`${process.env.FRONTEND_URL}/practice?token=${token}`);

      console.log("Successfully authenticated and generated token.");
    });
  })(req, res, next);
};

module.exports = casLogin;