const jwt = require("jsonwebtoken");
const jwtSecret = process.env.JWT_SECRET;
const filter = require("../utils/filter");
function generateJwtToken(username, user_id) {
  try {
    return jwt.sign({ username: username, user_id: user_id }, jwtSecret, {
      algorithm: "HS256",
      expiresIn: "30d",
    });
  } catch (e) {
    console.log("Failed to generate JWT token, ", e);
    throw e;
  }
}

function verifyJwtToken(token) {
  try {
    const decoded = jwt.verify(token, jwtSecret, { algorithms: ["HS256"] });
    if (!decoded?.user_id) {
      throw new Error("Token verification failed - missing user_id");
    }
    console.log("verifyJwtToken decoded: ", decoded);
    const username = filter(decoded.username);
    return { username: username, user_id: decoded.user_id };
  } catch (e) {
    console.error(e.message);
    throw e;
  }
}

module.exports = {
  generateJwtToken,
  verifyJwtToken,
};
