const { ensureFreshMsAccessToken } = require("../utils/msTokenService");

/**
 * Ensures Microsoft Graph access token is fresh and attaches it to req.msAccessToken
 * for downstream SharePoint / Graph handlers.
 */
const msTokenMiddleware = async (req, res, next) => {
  try {
    const companyId = req.user?.companyId;
    if (!companyId) {
      req.msAccessToken = null;
      return next();
    }
    req.msAccessToken = await ensureFreshMsAccessToken(companyId);
    next();
  } catch (e) {
    console.error("msTokenMiddleware:", e.message);
    req.msAccessToken = null;
    next();
  }
};

module.exports = msTokenMiddleware;
