const jwt = require("jsonwebtoken");
const { getJwtSecret } = require("../config/jwtSecret");

const SAT_AUD = "sat";
const SESSION_PURPOSE = "app-session";

function assertSessionToken(decoded) {
  if (!decoded || decoded.purpose !== SESSION_PURPOSE) {
    const error = new Error("App session token required");
    error.status = 401;
    throw error;
  }
  if (decoded.aud !== SAT_AUD) {
    const error = new Error("Invalid token audience for SAT API");
    error.status = 401;
    throw error;
  }
}

const verifyToken = (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;

    if (!authHeader) {
      return res.status(401).json({
        success: false,
        message: "Access denied. No token provided.",
      });
    }

    const token = authHeader.startsWith("Bearer ")
      ? authHeader.slice(7)
      : authHeader;

    if (!token) {
      return res.status(401).json({
        success: false,
        message: "Access denied. No token provided.",
      });
    }

    const decoded = jwt.verify(token, getJwtSecret());
    assertSessionToken(decoded);
    req.user = decoded;
    next();
  } catch (error) {
    if (error.status === 401) {
      return res.status(401).json({
        success: false,
        message: error.message,
      });
    }
    if (error.name === "TokenExpiredError") {
      return res.status(401).json({
        success: false,
        message: "Token has expired",
      });
    }
    if (error.name === "JsonWebTokenError") {
      return res.status(401).json({
        success: false,
        message: "Invalid token",
      });
    }
    console.error("Token verification error:", error);
    return res.status(500).json({
      success: false,
      message: "Token verification failed",
      error: error.message,
    });
  }
};

module.exports = verifyToken;
