const { AsyncLocalStorage } = require('async_hooks');

const requestContextStorage = new AsyncLocalStorage();

function initializeRequestContext(req, res, next) {
  requestContextStorage.run(
    {
      currentOrg: null,
      currentUserId: null,
      globalAccess: false,
      enforceOrganizationScope: false,
    },
    next,
  );
}

function getRequestContext() {
  return (
    requestContextStorage.getStore() || {
      currentOrg: null,
      currentUserId: null,
      globalAccess: false,
      enforceOrganizationScope: false,
    }
  );
}

function setRequestContextScope({ currentOrg = null, currentUserId = null, globalAccess = false, enforceOrganizationScope = false }) {
  const context = getRequestContext();

  context.currentOrg = currentOrg;
  context.currentUserId = currentUserId;
  context.globalAccess = Boolean(globalAccess);
  context.enforceOrganizationScope = Boolean(enforceOrganizationScope);

  return context;
}

function attachAuthenticatedRequestContext(req, res, next) {
  setRequestContextScope({
    currentOrg: req.currentUser?.organizationsId || null,
    currentUserId: req.currentUser?.id || null,
    globalAccess: req.currentUser?.app_role?.globalAccess,
    enforceOrganizationScope: true,
  });

  next();
}

module.exports = {
  initializeRequestContext,
  getRequestContext,
  setRequestContextScope,
  attachAuthenticatedRequestContext,
};
