const jwt = require("jsonwebtoken");
const jwtSecret = process.env.JWT_SECRET;

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) {
      console.error("Token verification failed - missing user_id");
      return { message: "Invalid token" };
    }

    if (!decoded?.username) {
      console.error("Token verification failed - missing username");
      return { message: "Invalid token" };
    }

    return { username: decoded.username, user_id: decoded.user_id };
  } catch (e) {
    console.error(e.message);
    return { message: "Authorization failed" };
  }
}

module.exports = {
  generateJwtToken,
  verifyJwtToken,
};
