const utils = require("../utils/auth.utils");
const logger = require("../utils/logger.utils");

module.exports = async function authCheck(req, res, next) {
  //log.out("authMiddlewares: Checking authentication", "dbug");
  logger.logger.debug("Auth check starting")
  try {
    var uuid = req.headers.uuid;
  } catch (err) {
    logger.logger.warn("Unable to read UUID header - Not authenticated")
    req.isAuthed = false;
    return next();
  }
  try {
    var result = (await utils.isAuthed(uuid)) || false;
    if (!result) {
      req.isAuthed = false;
      //log.out("authMiddlewares: User !isAuthed", "dbug");
      logger.logger.debug("Auth denied")
    } else {
      req.isAuthed = true;
      //log.out("authMiddlewares: User isAuthed", "dbug");
      logger.logger.debug("Auth successful")
    }
    return next();
  } catch (err) {
    /*log.out(
      "authMiddlewares: Unable to check auth, default to !isAuthed",
      "warn"
    );*/
    logger.logger.error(err, `Auth check failed`)
    req.isAuthed = false;
    return next(err);
  }
};
