import jwt from "jsonwebtoken";

export const verifyToken = async (req, res, next) => {
  try {
    let token = req.header("Authorization");

    if (!token) {
      return res.status(401).send("Access Denied, token missing");
    }

    if (token.startsWith("Bearer ")) {
      token = token.slice(7).trim();
    }

    const verified = jwt.verify(token, process.env.JWT_SECRET, {
      algorithms: ["HS256"],
      issuer: "mern-social",
    });

    req.user = verified;

    next();
  } catch (err) {
    console.error("JWT error: ", err.message);
    // res.status(500).json({ error: err.message + " wrong login" });
    return res.status(401).json({ msg: "expired or wrong token" });
  }
};

export const refresh = (req, res) => {
  console.log("try to refresh token");
  try {
    const refreshToken = req.cookies.refreshToken;

    if (!refreshToken) {
      return res.status(401).json({
        msg: "Missing refresh token",
      });
    }

    const verified = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET, {
      algorithms: ["HS256"],
      issuer: "mern-social",
    });

    // same configuratios as in auth.js controller, send new access token
    const accessToken = jwt.sign({ id: verified.id }, process.env.JWT_SECRET, {
      algorithm: "HS256",
      expiresIn: "15m",
      issuer: "mern-social",
    });
    return res.json({ token: accessToken });
  } catch (err) {
    return res.status(401).json({
      msg: "Invalid refresh token",
      // triggers refresh in frontend
    });
  }
};
