/**
 * Orchestrator login adapter for WESP login.html — persist JWT + enterprise after /api/auth/login.
 */
(function (global) {
  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-login.js",
        message,
        data,
        timestamp: Date.now(),
      }),
    }).catch(function () {});
    // #endregion
  }

  async function resolveEnterpriseId(accessToken) {
    try {
      const resp = await fetch("/api/v1/enterprise/enterprises", {
        headers: { Authorization: "Bearer " + accessToken },
      });
      if (!resp.ok) return "";
      const rows = await resp.json();
      return Array.isArray(rows) && rows[0] && rows[0].id ? String(rows[0].id) : "";
    } catch (_err) {
      return "";
    }
  }

  async function persistOrchestratorSession(payload) {
    const token = payload && payload.access_token ? String(payload.access_token) : "";
    const user = payload && payload.user ? payload.user : null;
    if (!token || !user) {
      debugLog("H2", "login missing token/user", { hasToken: Boolean(token), hasUser: Boolean(user) });
      return false;
    }
    const enterpriseId = await resolveEnterpriseId(token);
    if (global.ComptonWespAuth && typeof global.ComptonWespAuth.persistSession === "function") {
      global.ComptonWespAuth.persistSession(token, user, enterpriseId);
    }
    global.__WESP_ORCH__ = Object.assign({}, global.__WESP_ORCH__ || {}, {
      accessToken: token,
      enterpriseId: enterpriseId,
      userEmail: user.email || "",
    });
    debugLog("H1", "session persisted", { hasEnterprise: Boolean(enterpriseId), email: user.email || "" });
    return Boolean(enterpriseId);
  }

  const nativeFetch = global.fetch.bind(global);
  global.fetch = function orchestratorLoginFetch(input, init) {
    const url = typeof input === "string" ? input : input && input.url ? input.url : "";
    if (url.indexOf("/api/auth/login") === -1) {
      return nativeFetch(input, init);
    }
    debugLog("H3", "wesp login request", { url: url.split("?")[0] });
    return nativeFetch(input, init).then(async function (response) {
      const cloned = response.clone();
      let data = {};
      try {
        data = await cloned.json();
      } catch (_err) {
        debugLog("H3", "login response not json", { status: response.status });
        return response;
      }
      if (response.ok && data.status === "success") {
        await persistOrchestratorSession(data);
      } else {
        debugLog("H3", "login failed", { status: response.status, bodyStatus: data.status });
      }
      return response;
    });
  };

  debugLog("H4", "orchestrator login adapter ready", { path: global.location.pathname });
})(window);
