/**
 * Orchestrator login adapter for WESP login.html — persist JWT + enterprise after /api/auth/login.
 */
(function (global) {
  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) {
      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 || "",
    });
    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);
    }
    return nativeFetch(input, init).then(async function (response) {
      const cloned = response.clone();
      let data = {};
      try {
        data = await cloned.json();
      } catch (_err) {
        return response;
      }
      if (response.ok && data.status === "success") {
        await persistOrchestratorSession(data);
      }
      return response;
    });
  };
})(window);
