/**
 * Reads site JWT from localStorage and seeds __WESP_ORCH__ before zootech pages load.
 */
(function (global) {
  const TOKEN_KEY = "compton.access_token";
  const ENTERPRISE_KEY = "compton.enterprise_id";
  const USER_KEY = "compton.user";

  function readJson(key) {
    try {
      const raw = global.localStorage.getItem(key);
      return raw ? JSON.parse(raw) : null;
    } catch (_err) {
      return null;
    }
  }

  const token = global.localStorage.getItem(TOKEN_KEY) || "";
  const enterpriseId =
    global.localStorage.getItem(ENTERPRISE_KEY) ||
    new URLSearchParams(global.location.search).get("enterprise_id") ||
    "";
  const user = readJson(USER_KEY);

  let resolveReady;
  const ready = new Promise(function (resolve) {
    resolveReady = resolve;
  });

  function markReady() {
    if (typeof resolveReady === "function") {
      resolveReady();
      resolveReady = null;
    }
  }

  global.__WESP_ORCH__ = Object.assign({}, global.__WESP_ORCH__ || {}, {
    apiBase: "/api/v1",
    accessToken: token,
    enterpriseId: enterpriseId,
    userEmail: user && user.email ? user.email : "",
    ready: ready,
  });

  if (enterpriseId || !token) {
    markReady();
  } else {
    fetch("/api/v1/enterprise/enterprises", {
      headers: { Authorization: "Bearer " + token },
    })
      .then(function (resp) {
        return resp.ok ? resp.json() : [];
      })
      .then(function (rows) {
        const entId = Array.isArray(rows) && rows[0] && rows[0].id ? String(rows[0].id) : "";
        if (!entId) {
          return;
        }
        global.localStorage.setItem(ENTERPRISE_KEY, entId);
        global.__WESP_ORCH__ = Object.assign({}, global.__WESP_ORCH__ || {}, { enterpriseId: entId });
      })
      .catch(function () {})
      .finally(markReady);
  }

  global.ComptonWespAuth = {
    TOKEN_KEY,
    ENTERPRISE_KEY,
    USER_KEY,
    persistSession(accessToken, userPayload, entId) {
      if (accessToken) global.localStorage.setItem(TOKEN_KEY, accessToken);
      if (userPayload) global.localStorage.setItem(USER_KEY, JSON.stringify(userPayload));
      if (entId) global.localStorage.setItem(ENTERPRISE_KEY, entId);
      global.__WESP_ORCH__ = Object.assign({}, global.__WESP_ORCH__ || {}, {
        accessToken: accessToken || "",
        enterpriseId: entId || "",
        userEmail: userPayload && userPayload.email ? userPayload.email : "",
      });
    },
    clearSession() {
      global.localStorage.removeItem(TOKEN_KEY);
      global.localStorage.removeItem(ENTERPRISE_KEY);
      global.localStorage.removeItem(USER_KEY);
    },
  };
})(window);
