import { SETUP_ENDPOINT_PATH as P, SETUP_ENDPOINTS_API_VERSIONS as u } from "./constants.js";
import { parseSearchParams as E } from "../../Http/utils.js";
import { encodeAnalyticsEvent as g } from "../../Analytics/analytics/utils.js";
import { noop as c, deepFreeze as x } from "../../../utils/common.js";
import { EMPTY_OBJECT as n } from "../../../utils/value/constants.js";
import { createPromisor as v } from "../../../primitives/async/promisor/main.js";
import { struct as T, withFreezeProxyHandlers as b, asPlainObject as O } from "../../../utils/struct/main.js";
import { isPlainObject as S, isUndefined as k } from "../../../utils/value/is.js";
import { isAbortSignal as w, abortSignalForAny as A } from "../../../utils/abort/main.js";
class R {
  constructor(t) {
    this._session = t;
    let e;
    this.refresh = (r) => (this._refreshPromisor(r).catch(c), e ??= this._refreshPromisor.promise.finally(() => e = void 0).then(({ endpoints: o, ...i }) => {
      this._resetEndpoints(), { proxy: this._endpoints, revoke: this._revokeEndpointsProxy } = this._getEndpointsProxy(o), this._extraConfig = x(i), this.analyticsEnabled && this._setAnalyticsUserProfile()?.then(() => {
        this.setCustomTranslationsAnalytics();
      });
    }));
  }
  _endpoints = n;
  _extraConfig = n;
  _revokeEndpointsProxy = c;
  _beforeHttp = async () => {
    await this._refreshPromisor.promise.catch(c);
  };
  _refreshPromisor = v((t, e) => {
    const r = w(e) ? A([e, t]) : t;
    return this._fetchSetupEndpoint(r);
  });
  get endpoints() {
    return this._endpoints;
  }
  get extraConfig() {
    return this._extraConfig;
  }
  _fetchSetupEndpoint(t) {
    return this._session.http(null, {
      method: "POST",
      path: P,
      errorLevel: "fatal",
      loadingContext: this.loadingContext,
      signal: t
    });
  }
  async _setAnalyticsUserProfile() {
    const t = g([{}]);
    if (this._endpoints.sendEngageEvent && t)
      return this._endpoints.sendEngageEvent(
        {
          body: t,
          contentType: "application/x-www-form-urlencoded",
          keepalive: !0
        },
        n
      );
  }
  async setCustomTranslationsAnalytics() {
    if (this.analyticsPayload && this.analyticsPayload?.length > 0 && this._endpoints && this._endpoints.sendTrackEvent) {
      const t = [];
      Promise.all(
        this.analyticsPayload.map((e) => this._endpoints.sendTrackEvent(
          {
            body: e,
            contentType: "application/x-www-form-urlencoded",
            keepalive: !0
          },
          n
        ).catch(() => {
          t.push(e);
        }))
      ).finally(() => {
        this.analyticsPayload = t.length > 0 ? t : void 0;
      });
    }
  }
  _getEndpointsProxy(t) {
    const e = new Set(Object.keys(t)), r = T();
    let o = !0;
    const i = () => {
      o = !1, e.clear();
    };
    return { proxy: new Proxy(
      n,
      b({
        get: (a, s, h) => {
          if (!o || !e.has(s))
            return Reflect.get(a, s, h);
          const p = u[s], f = p ? { apiVersion: p } : n;
          return r[s] ??= (() => {
            const { method: _ = "GET", url: d } = t[s];
            if (!k(d || void 0))
              return ((...y) => {
                const m = {
                  ...this._getHttpOptions(_, d, ...y),
                  ...f
                };
                return this._session.http(this._beforeHttp, m);
              });
          })(), r[s];
        }
      })
    ), revoke: i };
  }
  _getHttpOptions(t, e, ...r) {
    const { loadingContext: o } = this, [i, l] = r, { path: a, query: s } = O(l), h = s && E(s);
    if (S(a))
      for (const p of Object.keys(a))
        e = e.replace(`{${p}}`, a[p]);
    return { loadingContext: o, ...i, method: t, params: h, path: e };
  }
  _resetEndpoints() {
    this._revokeEndpointsProxy(), this._revokeEndpointsProxy = c, this._endpoints = n;
  }
}
export {
  R as SetupContext,
  R as default
};
