/**
 * 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";
  const DEBUG_ENDPOINT = "http://127.0.0.1:7898/ingest/d209dffb-c63e-477b-8b08-a57520eaee9b";
  const SESSION = "785e22";

  function debugLog(hypothesisId, message, data) {
    // #region agent log
    fetch(DEBUG_ENDPOINT, {
      method: "POST",
      headers: { "Content-Type": "application/json", "X-Debug-Session-Id": SESSION },
      body: JSON.stringify({
        sessionId: SESSION,
        runId: "login-fix",
        hypothesisId,
        location: "wesp-orchestrator-auth-bridge.js",
        message,
        data,
        timestamp: Date.now(),
      }),
    }).catch(function () {});
    // #endregion
  }

  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);

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

  debugLog("H1", "auth bridge init", {
    hasToken: Boolean(token),
    hasEnterprise: Boolean(enterpriseId),
    path: global.location.pathname,
  });

  if (token && !enterpriseId) {
    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) {
          debugLog("H1", "enterprise resolve failed", { count: Array.isArray(rows) ? rows.length : -1 });
          return;
        }
        global.localStorage.setItem(ENTERPRISE_KEY, entId);
        global.__WESP_ORCH__ = Object.assign({}, global.__WESP_ORCH__ || {}, { enterpriseId: entId });
        debugLog("H1", "enterprise resolved async", { enterpriseId: entId });
      })
      .catch(function () {
        debugLog("H1", "enterprise resolve error", {});
      });
  }

  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);
