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