import { getQueryParameter as J, removeQueryParametersForSeamlessRouter as Q } from "@b2x/std/core/url.mjs";
import { CONNECTIONS as y } from "@b2x/std/constants.mjs";
import { storage as g } from "@b2x/std/core/storage.mjs";
import { SeamlessConnection as Y, initializeStore as L } from "@seamless/store";
import { formatBuildTime as q } from "@b2x/shared/metadata.mjs";
import { isDebuggerEnable as X, isDebuggerGrouped as Z } from "@b2x/std/core/debug.mjs";
import { isLocalhost as ee } from "@b2x/std/core/utilities.mjs";
import { consola as U, BrowserReporter as te } from "@b2x/std/logger.mjs";
import { identifyTenant as u } from "@b2x/std/helpers/identify-tenant.mjs";
import { defineStore as D } from "@b2x/std/store.mjs";
import { createBroadcastChannel as ae } from "@b2x/std/core/broadcast.mjs";
import { getEnvironmentData as B } from "@b2x/shared/utilities.mjs";
import { createHttpClient as ne } from "@b2x/std/core/http.mjs";
import { BUSINESS_TYPE as re, subscribe as se } from "@b2x/profile-library";
const d = "B2X@AUTH";
function ie() {
  return U.setLogger(d, {
    reporters: [
      new te({
        title: `AUTH@0.29.0-${q("")}`,
        namespace: d,
        delay: 1500,
        grouped: Z(d),
        enabled: X(d) || ee()
      })
    ]
  }), {
    createLogger: (e) => U.createLoggerGroup(d, e)
  };
}
const h = ie(), G = ae("b2x-auth-channel"), E = {
  LOGIN: "LOGIN",
  LOGOUT: "LOGOUT",
  REGISTER: "REGISTER",
  LINKOUT: "LINKOUT"
}, r = {
  PROVIDER: "b2xProvider",
  FLOW: "b2xFlow",
  ERROR: "b2xError",
  CIAS_ERROR: "error",
  TOKEN: "token",
  REGISTER: "b2xRegister",
  B2B_REGISTRATION: "company-profile",
  LINKOUT_CODE: "linkout_code"
}, m = {
  CIAS: "CIAS"
}, A = {
  ONEWEB: "oneweb"
}, N = {
  ENABLED: "enabled",
  DISABLED: "disabled"
}, oe = 300;
function b(e) {
  globalThis.location.assign(e);
}
const R = async () => {
  const e = (await B("authentication")).pageEnvironmentVariables;
  return {
    stage: e.stage,
    language: e.language,
    country: e.country,
    runMode: e.runMode
  };
};
async function j() {
  const e = (await B("authentication")).componentData;
  return Object.values(e).some((t) => t.config?.userSessionRequired);
}
const ce = "https://test.api.oneweb.mercedes-benz.com/cias/v1/", C = "https://int.api.oneweb.mercedes-benz.com/cias/v1/", le = "https://api.oneweb.mercedes-benz.com/cias/v1/", ue = {
  DEV: ce,
  TEST: C,
  INT: C,
  PPROD: C,
  PROD: le
};
async function S() {
  const e = (await R()).stage;
  return ue[e];
}
const v = h.createLogger("LOGOUT_CIAS");
async function F({ targetUrl: e = globalThis.location.href } = {}) {
  const t = new URL(e);
  if (await j()) {
    t.pathname = "/", globalThis.location.pathname.includes("vans") && (t.pathname = "/vans");
    const c = /* @__PURE__ */ new Set([r.ERROR]);
    for (const P of t.searchParams.keys())
      c.has(P) || t.searchParams.delete(P);
  }
  t.searchParams.append(r.PROVIDER, m.CIAS), t.searchParams.append(r.FLOW, E.LOGOUT);
  const a = encodeURIComponent(t.toString()).length;
  a >= oe && (v.warn(`Target URL length (${a}) exceeds CIAM redirect limit. Redirecting to fallback URL.`), t.href = de());
  const { country: n, language: s } = await R(), i = {
    locale: `${s}_${n}`,
    tenantId: "oneweb",
    targetUrl: t.toString()
  }, o = new URL("logout", await S());
  o.search = new URLSearchParams(i).toString(), v.info("Logout action on CIAS to url:", o), b(o);
}
async function He() {
  await x({
    jwe: null,
    claims: null,
    identityProvider: null
  }), G.send({ type: "logout", payload: null });
}
function de() {
  const e = new URL(globalThis.location.origin);
  return e.searchParams.append(r.PROVIDER, m.CIAS), e.searchParams.append(r.FLOW, E.LOGOUT), e.toString();
}
const ge = h.createLogger("REGISTER_CIAS");
async function pe() {
  try {
    return (await new Promise((t) => {
      let a = () => {
      };
      a = se((n) => {
        a(), t(n);
      });
    }))?.activeProfile?.businessType || null;
  } catch (e) {
    return ge.warn("Could not get business type from Profile Library", e), null;
  }
}
async function he({ isB2BRegistrationEnabled: e = !1 } = {}) {
  const t = new URL(globalThis.location.href);
  t.searchParams.append(r.PROVIDER, m.CIAS), t.searchParams.append(r.FLOW, E.LOGIN), t.searchParams.append(r.REGISTER, "true");
  const { country: a, language: n } = await R(), s = {
    redirectUrl: t.toString(),
    tenantId: A.ONEWEB,
    locale: `${n}_${a}`
  };
  if (e) {
    const c = await pe() === re.B2B ? N.ENABLED : N.DISABLED;
    s[r.B2B_REGISTRATION] = c;
  }
  const i = new URL("registration", await S());
  i.search = new URLSearchParams(s).toString(), b(i);
}
const w = D({
  jwe: null,
  claims: null,
  identityProvider: null
});
w.defineGetter("isLoggedIn", (e) => !!e.jwe);
w.defineGetter("isProviderCias", (e) => e.identityProvider === "CIAS");
w.defineGetter("isMfaEnabled", (e) => e.claims?.acr === "mfa");
const p = D({
  jwe: null,
  isMfaEnabled: !1,
  email: null
});
p.defineGetter("isLoggedIn", (e) => !!e.jwe);
const me = h.createLogger("legacy-connection");
var we = /* @__PURE__ */ ((e) => (e.CIAS = "CIAS", e))(we || {}), fe = /* @__PURE__ */ ((e) => (e.ONEWEB = "oneweb", e.OFLOGIN = "OFLOGIN", e.CIAS = "cias", e.MARKETPLACE_CORE = "mrkplc-core", e))(fe || {}), ye = /* @__PURE__ */ ((e) => (e.ERROR = "ERROR", e.WARNING = "WARNING", e.SUCCESS = "SUCCESS", e.HIGHLIGHT = "HIGHLIGHT", e))(ye || {});
const $e = () => Promise.resolve(!0), We = () => Promise.resolve(!0);
class Ee extends Y {
  internalDispatch = null;
  errorCallbacks = [];
  alert = null;
  constructor() {
    super(y.AUTH_CONNECTION_NAME);
  }
  get initialState() {
    return Object.seal(this.internalState);
  }
  get internalState() {
    const t = w.state, a = {
      jwe: t.jwe,
      claims: t.claims,
      identityProvider: "CIAS",
      isPending: !1
    };
    return new Proxy(a, {
      get: (n, s, i) => (this.showDeprecationWarning(), u("iam", "SDS"), Reflect.get(n, s, i))
    });
  }
  showDeprecationWarning() {
    me.warn(
      `${y.AUTH_CONNECTION_NAME} is deprecated. Please migrate to the new API: https://pages.git.i.mercedes-benz.com/dh-io-iam/iam-frontend/authn-library/about.html`
    );
  }
  getDefaultProvider(t) {
    return t?.identityProvider ?? "CIAS";
  }
  onBeforeRegister(t) {
    this.internalDispatch = t;
  }
  setState(t) {
    this.internalDispatch(this.getAction("SET_STATE", t));
  }
  setError(t) {
    t && (this.alert = Object.create(t), this.alert?.type === "BASIC" && (this.alert.type = "HIGHLIGHT"), this.errorCallbacks.forEach((a) => {
      a({ data: this.alert });
    }));
  }
  getPublicDispatchers() {
    return {
      login: (t) => (this.showDeprecationWarning(), u("iam", "sds-login"), () => Pe(t)),
      logout: (t) => (this.showDeprecationWarning(), u("iam", "sds-logout"), () => F(t)),
      register: () => (this.showDeprecationWarning(), u("iam", "sds-register"), he),
      alert: (t) => (this.showDeprecationWarning(), u("iam", "sds-alert"), (a) => {
        a(() => this.errorCallbacks.push(t)), this.alert && t({ data: this.alert });
      })
    };
  }
  getReducer() {
    return (t, a) => a.type === "SET_STATE" ? {
      ...a.payload,
      isPending: !1,
      identityProvider: "CIAS"
      /* CIAS */
    } : this.internalState;
  }
}
const I = new Ee();
g.local.remove(`swsp:${y.AUTH_CONNECTION_NAME}`);
async function Re(e, t) {
  const a = crypto.getRandomValues(new Uint8Array(16)), n = await k(t, a), s = crypto.getRandomValues(new Uint8Array(12)), i = K(e), o = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: s }, n, i));
  return {
    salt: O(a),
    iv: O(s),
    cipher: O(o)
  };
}
async function Se(e, t) {
  const a = T(e.salt), n = await k(t, a), s = T(e.iv), i = T(e.cipher), o = new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: s }, n, i));
  return Ce(o);
}
async function k(e, t) {
  const a = K(e), n = await crypto.subtle.importKey("raw", a, { name: "PBKDF2" }, !1, ["deriveKey"]);
  return crypto.subtle.deriveKey(
    { name: "PBKDF2", salt: t, iterations: 1e5, hash: "SHA-256" },
    n,
    { name: "AES-GCM", length: 256 },
    !1,
    ["encrypt", "decrypt"]
  );
}
function Ce(e) {
  return new TextDecoder().decode(e);
}
function K(e) {
  return new TextEncoder().encode(e);
}
function O(e) {
  return btoa(Array.from(e, (t) => String.fromCodePoint(t)).join(""));
}
function T(e) {
  return Uint8Array.from(atob(e), (t) => t.codePointAt(0));
}
class Ie {
  storageKey = "b2x.auth-state";
  key = "key";
  initialState = {
    jwe: null,
    claims: null,
    identityProvider: null
  };
  decryptedState = null;
  async get() {
    if (this.decryptedState)
      return this.decryptedState;
    const t = g.local.get(this.storageKey);
    if (!t)
      return this.initialState;
    const a = await Se(t, this.key);
    return this.decryptedState = JSON.parse(a), this.decryptedState;
  }
  async set(t) {
    this.decryptedState = t;
    const a = JSON.stringify({
      jwe: t.jwe,
      claims: t.claims,
      identityProvider: t.identityProvider
    }), n = await Re(a, this.key);
    g.local.set(this.storageKey, n);
  }
  remove() {
    g.local.remove(this.storageKey), this.decryptedState = null;
  }
}
const _ = new Ie(), Oe = h.createLogger("PUBLISH_STATE");
async function x(e) {
  Oe.info("publishing state", e), w.updateState(e), p.updateState({
    jwe: e.jwe,
    isMfaEnabled: e.claims?.acr === "mfa",
    email: e.claims?.email
  }), await L().getConnectionDispatchers(y.AUTH_CONNECTION_NAME, 5).then(() => !0).catch(() => !1) ? (I.setState(e), I.setError(null)) : await L().addConnection(I), g.session.set("ow_aem_loginstate", e.jwe ? "logged_in" : "logged_out", !1), e?.jwe ? await _.set(e) : _.remove();
}
class l extends Error {
  // name has to be defined in the derived class because of minification
  type = "";
  translationKey = "";
  get shouldNotify() {
    return !!this.type;
  }
  toString() {
    return `[${this.id}]: ${this.message}`;
  }
}
const f = {
  ERROR: "ERROR"
};
class Te extends l {
  id = "UnknownError";
  type = f.ERROR;
  translationKey = "error.unknown";
  constructor() {
    super("Authorization: Unexpected error occurred. Please try later.");
  }
}
class M extends l {
  id = "CiasMissingToken";
  type = f.ERROR;
  translationKey = "error.login";
  constructor() {
    super("Cias is missing token");
  }
}
class H extends l {
  id = "CiasFailureFetchJwt";
  type = f.ERROR;
  translationKey = "error.login";
  constructor() {
    super("Cias failed exchanging token to jwe");
  }
}
class $ extends l {
  id = "CiasFailureFetchClaims";
  type = f.ERROR;
  translationKey = "error.login";
  constructor() {
    super("Cias failed obtaining claims");
  }
}
class W extends l {
  id = "CiasValidationError";
  type = f.ERROR;
  translationKey = "error.login";
  constructor() {
    super("Cias failed validating token");
  }
}
class z extends l {
  id = "CiasFailureRefreshJwt";
  translationKey = "error.refresh";
  constructor() {
    super("Cias failed refresh jwe");
  }
}
const Ae = [
  M,
  H,
  $,
  W,
  z
];
function ze(e) {
  const t = Ae.find((a) => new a().id === e) || Te;
  return new t();
}
async function be() {
  const e = ne({ prefixUrl: await S() });
  return {
    fetchJwe: async (t) => {
      try {
        return (await e.get(`jwe/${t}`))?.text();
      } catch {
        throw new H();
      }
    },
    fetchClaims: async (t) => {
      try {
        return await (await e.put("claims", {
          headers: {
            Accept: "application/json",
            ApplicationName: "b2xlc",
            Authorization: `Bearer ${t}`
          },
          searchParams: {
            scope: "FULL_NO_CIAM_ID"
          }
        })).json();
      } catch {
        throw new $();
      }
    },
    validate: async (t) => {
      try {
        return await (await e.get("validation", {
          headers: {
            Accept: "application/json",
            ApplicationName: "b2xlc",
            Authorization: `Bearer ${t}`
          }
        })).json();
      } catch {
        throw new W();
      }
    },
    refreshToken: async (t) => {
      try {
        return (await (await e.post("jwe/refresh", {
          headers: {
            accept: "application/json",
            tenantId: A.ONEWEB,
            Authorization: `Bearer ${t}`
          }
        })).json()).jwe;
      } catch {
        throw new z();
      }
    }
  };
}
const V = h.createLogger("LOGIN_CIAS");
async function Pe({
  redirectUrl: e = globalThis.location.href,
  mfa: t = !1,
  linkoutCode: a
} = {}) {
  if (p.state.isLoggedIn && !t)
    throw new Error("There is active session already, cannot start a new one");
  if (p.state.isLoggedIn && t && p.state.isMfaEnabled)
    throw new Error("There is active session with mfa already, cannot start a new one");
  const n = new URL(e);
  n.searchParams.append(r.PROVIDER, m.CIAS), n.searchParams.append(r.FLOW, E.LOGIN);
  const { country: s, language: i } = await R(), o = {
    prompt: "DEFAULT",
    locale: `${i}_${s}`,
    tenantId: A.ONEWEB,
    redirectUrl: n.toString(),
    // It is called a USVString which is different from the JavaScript string type
    forceMfa: String(t)
  };
  a && (o[r.LINKOUT_CODE] = a);
  const c = new URL("authentication", await S());
  c.search = new URLSearchParams(o).toString(), V.info("Login action on CIAS to url:", c), b(c);
}
async function Ve() {
  V.info("Running CIAS login flow");
  let e = {
    jwe: null,
    claims: null,
    identityProvider: null
  };
  try {
    const t = await be(), a = J(r.TOKEN);
    if (Q([r.TOKEN, r.REGISTER]), !a)
      throw new M();
    const n = await t.fetchJwe(a), s = await t.fetchClaims(n);
    e = {
      jwe: n,
      claims: s,
      identityProvider: m.CIAS
    };
  } catch (t) {
    if (await j()) {
      const a = new URL(globalThis.location.href);
      return a.searchParams.append(r.ERROR, t.id), F({ targetUrl: a.toString() });
    }
    throw t;
  } finally {
    await x(e), G.send({ type: "login", payload: e });
  }
}
export {
  ye as A,
  E as F,
  we as I,
  f as N,
  m as P,
  r as Q,
  fe as T,
  Te as U,
  Pe as a,
  p as b,
  We as c,
  h as d,
  be as e,
  j as f,
  _ as g,
  ze as h,
  $e as i,
  Ve as j,
  He as k,
  F as l,
  R as m,
  l as n,
  I as o,
  x as p,
  w as q,
  he as r,
  G as s
};
//# sourceMappingURL=cias-login.mjs.map
