const logger = require("../utils/logger");
const admin = require("firebase-admin");

/**
 *  Middleware to validate Firebase ID Tokens.
 *  This middleware is used to protect API endpoints from unauthorized access.
 *  It adds the following properties to the request object:
 *  - req.user - the decoded Firebase ID Token
 * @param req
 * @param res
 * @param next
 * @returns {Promise<void>}
 */
const validateFirebaseIdTokenMiddleware = async (req, res, next) => {
  if (
    (!req.headers.authorization || !req.headers.authorization.startsWith("Bearer ")) &&
    !(req.cookies && req.cookies.__session)
  ) {
    logger.log("api-authorization-call", "warn", req?.user?.email, null, {
      type: "unauthorized",
      path: req.path,
      body: req.body
    });
    return res.status(403).send("Unauthorized");
  }

  let idToken;

  if (req.headers.authorization && req.headers.authorization.startsWith("Bearer ")) {
    // console.log('Found "Authorization" header');
    // Read the ID Token from the Authorization header.
    idToken = req.headers.authorization.split("Bearer ")[1];
  } else if (req.cookies) {
    //console.log('Found "__session" cookie');
    // Read the ID Token from cookie.
    idToken = req.cookies.__session;
  } else {
    // No cookie
    logger.log("api-unauthorized-call", "warn", null, null, {
      type: "unauthorized",
      path: req.path,
      body: req.body
    });

    return res.status(403).send("Unauthorized");
  }

  try {
    const decodedIdToken = await admin.auth().verifyIdToken(idToken);
    //console.log("ID Token correctly decoded", decodedIdToken);
    req.user = decodedIdToken;
    next();
  } catch (error) {
    logger.log("api-unauthorized-call", "warn", null, null, {
      path: req.path,
      body: req.body,

      type: "unauthorized",
      ...error
    });

    return res.status(401).send("Unauthorized");
  }
};

module.exports = validateFirebaseIdTokenMiddleware;
