import { ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT as $, ERROR_CODE_TOKEN_EXPIRED as Y, ERROR_CODE_LINK_DELETION_ACCOUNT as J, ERROR_USER_BANNED as tt, DesktopChecker as b } from "@accelbyte/sdk";
import { F as a, e as B, u as O, f as W, W as f, E as V, L as M, b as et } from "./FetchConfigsUtils-476a602b.mjs";
import { useCallback as o, useRef as v, useEffect as K } from "react";
import "./SSRHelper-8eb361ff.mjs";
import { u as rt, a as st } from "./useUserInfo-ad7006e5.mjs";
import { z as w } from "zod";
import { Gdpr as P } from "@accelbyte/sdk-gdpr";
import { Legal as H, LegalHelper as at } from "@accelbyte/sdk-legal";
import { u as nt } from "./useDiscoveryConfigs-cf63cd60.mjs";
import { ConflictedUserPlatformAccounts as ot, Iam as m, IamUserAuthorizationClient as X, UpgradeHeadlessAccountWithVerificationCodeRequestV3 as lt, UpgradeHeadlessAccountWithVerificationCodeRequestV4 as ct, TokenResponseV3 as ut, IamHelper as it } from "@accelbyte/sdk-iam";
import { Basic as dt } from "@accelbyte/sdk-basic";
const j = {
  eligibilities: null,
  eligibilitiesError: null,
  eligibilitiesFetchStatus: a.IDLE,
  policiesByCountry: null,
  policiesError: null,
  policiesFetchStatus: a.IDLE,
  bulkAcceptPoliciesError: null,
  bulkAcceptPoliciesFetchStatus: a.IDLE,
  acceptedAgreements: null,
  acceptedAgreementsError: null,
  acceptedAgreementsFetchStatus: a.IDLE
}, Et = B(j);
function pt() {
  const [e] = O(), [d, r] = W(Et), D = o(() => {
    r(j);
  }, []), L = o(async () => {
    let g = null, E = null;
    try {
      r({ eligibilitiesError: null, eligibilitiesFetchStatus: a.FETCHING });
      const A = await H.EligibilitiesApi(e).getEligibility_ByNamespace();
      return g = at.getUnsignedPolicies(A), { data: g };
    } catch (A) {
      return E = f.getErrorType(A), { error: E };
    } finally {
      r({ eligibilities: g, eligibilitiesError: E, eligibilitiesFetchStatus: a.IDLE });
    }
  }, [e]), y = o(
    async (g, E = !0) => {
      let A = null, h = null;
      try {
        return r({ policiesError: null, policiesFetchStatus: a.FETCHING }), A = await H.PoliciesApi(e).getPolicyCountry_ByCountryCode_ByNS(g, { defaultOnEmpty: E }), { data: A };
      } catch (F) {
        return h = f.getErrorType(F), { error: h };
      } finally {
        r({ policiesByCountry: A, policiesError: h, policiesFetchStatus: a.IDLE });
      }
    },
    [e]
  ), T = o(
    async (g) => {
      let E = null;
      try {
        return r({ bulkAcceptPoliciesError: null, bulkAcceptPoliciesFetchStatus: a.FETCHING }), { data: await H.AgreementApi(e).createAgreementPolicy(g) };
      } catch (A) {
        return E = f.getErrorType(A), { error: E };
      } finally {
        r({ bulkAcceptPoliciesError: E, bulkAcceptPoliciesFetchStatus: a.IDLE });
      }
    },
    [e]
  ), R = o(async () => {
    let g = null, E = null;
    try {
      return r({ acceptedAgreementsError: null, acceptedAgreementsFetchStatus: a.FETCHING }), g = await H.AgreementApi(e).getAgreementsPolicies(), { data: g };
    } catch (A) {
      return E = f.getErrorType(A), { error: E };
    } finally {
      r({ acceptedAgreements: g, acceptedAgreementsError: E, acceptedAgreementsFetchStatus: a.IDLE });
    }
  }, [e]);
  return {
    state: d,
    mutations: {
      resetState: D,
      fetchUnsignedPolicies: L,
      fetchPoliciesList: y,
      bulkAcceptPolicies: T,
      fetchAcceptedAgreements: R
    }
  };
}
var U = /* @__PURE__ */ ((e) => (e.USER = "USER", e.ACCESS_TOKEN = "ACCESS_TOKEN", e.REFRESH_TOKEN = "REFRESH_TOKEN", e.SETTINGS = "SETTINGS", e.IS_WINDOW_MAXIMIZED = "IS_WINDOW_MAXIMIZED", e.FEATURE_FLAGS = "FEATURE_FLAGS", e.APP_CONFIG = "APP_CONFIG", e.DOWNLOAD_STATE = "DOWNLOAD_STATE", e.LAST_VISITED_GAME = "LAST_VISITED_GAME", e.LAST_VISITED_PAGE = "LAST_VISITED_PAGE", e.IS_LAUNCHER_UPDATE_CHECKED = "IS_LAUNCHER_UPDATE_CHECKED", e))(U || {});
class At {
  constructor(d) {
    this.desktopStorage = d;
  }
  clear() {
    this.desktopStorage.clear();
  }
  delete(d) {
    this.desktopStorage.remove(d);
  }
  get(d) {
    return this.desktopStorage.get(d);
  }
  set(d, r) {
    this.desktopStorage.set(d, r);
  }
  getUser() {
    return this.desktopStorage.get("USER");
  }
  getAccessToken() {
    return this.desktopStorage.get("ACCESS_TOKEN");
  }
  getRefreshToken() {
    return this.desktopStorage.get("REFRESH_TOKEN");
  }
  getDownloadState(d) {
    var r;
    return (r = this.desktopStorage.get("DOWNLOAD_STATE")) == null ? void 0 : r.find((D) => D.appId === d);
  }
  getLastVisitedGame() {
    return this.desktopStorage.get("LAST_VISITED_GAME");
  }
  getLastVisitedPage() {
    return this.desktopStorage.get("LAST_VISITED_PAGE");
  }
  getIsLauncherUpdateChecked() {
    return !!this.desktopStorage.get("IS_LAUNCHER_UPDATE_CHECKED");
  }
}
const x = w.enum(["MARKED", "MARK_IGNORED"]), z = {
  deletionMark: null,
  gdprDeletionStatus: null,
  gdprDeletionError: null,
  gdprDeletionFetchStatus: a.IDLE,
  requestDeletionFetchStatus: a.IDLE,
  requestDeletionError: null,
  gdprDataRequestList: null,
  gdprDataRequestListError: null,
  gdprDataRequestListFetchStatus: a.IDLE,
  gdprRequestFetchStatus: a.IDLE,
  isAccountDeletionSuccessPageLocked: !1
}, gt = B(z);
function St() {
  const [e] = O(), [d, r] = W(gt), D = o(() => {
    r(z);
  }, []), L = o(
    async (n) => {
      let s = null, t = null;
      try {
        return r({ gdprDeletionError: null, gdprDeletionFetchStatus: a.FETCHING }), s = await P.DataDeletionApi(e).getDeletionsStatus_ByUserId(n), { data: s };
      } catch (l) {
        return t = f.getErrorType(l), { error: l };
      } finally {
        r({ gdprDeletionStatus: s, gdprDeletionError: t, gdprDeletionFetchStatus: a.IDLE });
      }
    },
    [e]
  ), y = o(() => {
    r({ deletionMark: x.Enum.MARKED });
  }, []), T = o(() => {
    r({ deletionMark: x.Enum.MARK_IGNORED });
  }, []), R = o(
    async (n) => {
      let s = null;
      try {
        return r({ requestDeletionError: s, requestDeletionFetchStatus: a.CANCELLING }), await P.DataDeletionApi(e).deleteDeletion_ByUserId(n), { data: null };
      } catch (t) {
        return s = f.getErrorType(t), { error: t };
      } finally {
        r({ requestDeletionError: s, requestDeletionFetchStatus: a.IDLE });
      }
    },
    [e]
  ), g = o(
    async (n, s) => {
      let t = null;
      try {
        return r({ requestDeletionError: t, requestDeletionFetchStatus: a.REQUESTING }), { data: await P.DataDeletionApi(e).postDeletion_ByUserId(n, { password: s }) };
      } catch (l) {
        return t = f.getErrorType(l), { error: l };
      } finally {
        r({ requestDeletionError: t, requestDeletionFetchStatus: a.IDLE });
      }
    },
    [e]
  ), E = o((n) => {
    r({ isAccountDeletionSuccessPageLocked: n });
  }, []), A = o((n) => {
    r({ gdprDataRequestListFetchStatus: n });
  }, []), h = o(
    async (n, s, t) => {
      let l = null, c = null;
      try {
        return r({ gdprDataRequestListError: c, gdprDataRequestListFetchStatus: a.FETCHING }), l = await P.DataRetrievalApi(e).getRequests_ByUserId(n, { offset: s, limit: t }), { data: l };
      } catch (p) {
        return c = f.getErrorType(p), { error: p };
      } finally {
        r({
          gdprDataRequestList: l,
          gdprDataRequestListError: c,
          gdprDataRequestListFetchStatus: a.IDLE
        });
      }
    },
    [e]
  ), F = o(
    async (n, s) => {
      try {
        return r({ gdprRequestFetchStatus: a.REQUESTING }), { data: await P.DataRetrievalApi(e).postRequest_ByUserId(s, { password: n }) };
      } catch (t) {
        return { error: t };
      } finally {
        r({ gdprRequestFetchStatus: a.IDLE });
      }
    },
    [e]
  ), N = o(
    async (n, s) => {
      try {
        return r({ gdprRequestFetchStatus: a.CANCELLING }), await P.DataRetrievalApi(e).deleteRequest_ByUserId_ByRequestDate(s, n), { data: null };
      } catch (t) {
        return { error: t };
      } finally {
        r({ gdprRequestFetchStatus: a.IDLE });
      }
    },
    [e]
  ), u = o(
    async (n, s, t) => {
      try {
        return r({ gdprRequestFetchStatus: a.DOWNLOADING }), { data: await P.DataRetrievalApi(e).postGenerate_ByUserId_ByRequestDate(t, n, { password: s }) };
      } catch (l) {
        return { error: l };
      } finally {
        r({ gdprRequestFetchStatus: a.IDLE });
      }
    },
    [e]
  );
  return {
    state: d,
    mutations: {
      resetState: D,
      fetchGdprDeletionStatus: L,
      markForDeletion: y,
      ignoreDeletionMark: T,
      cancelDeleteAccount: R,
      deleteAccount: g,
      updateAccountDeletionSuccessPageLocked: E,
      updateGdprDataRequestListFetchStatus: A,
      fetchGdprRequestDataList: h,
      requestGdprData: F,
      cancelRequestGdprData: N,
      downloadGdprData: u
    }
  };
}
const ft = w.object({
  errorCode: w.number(),
  errorMessage: w.string(),
  messageVariables: ot
}), Q = {
  linkedPlatform: null,
  linkedPlatformFetchStatus: a.IDLE,
  linkedPlatformError: null,
  linkAccountFetchStatus: a.IDLE,
  linkAccountError: null,
  unlinkAccountFetchStatus: a.IDLE,
  unlinkAccountError: null,
  upgradeHeadlessAccountFetchStatus: a.IDLE,
  upgradeHeadlessAccountError: null,
  accountConflictInformation: null,
  requestStatusFetchStatus: a.IDLE,
  requestStatusError: null
}, Dt = B(Q);
function ht() {
  const [e] = O(), [d, r] = W(Dt), D = o(() => {
    r(Q);
  }, []), L = o(() => {
    r({
      linkedPlatformError: null,
      linkAccountError: null,
      unlinkAccountError: null,
      upgradeHeadlessAccountError: null,
      accountConflictInformation: null,
      requestStatusError: null
    });
  }, []), y = o(
    async (u) => {
      let n = null, s = null;
      try {
        return r({ linkedPlatformError: null, linkedPlatformFetchStatus: a.FETCHING }), n = (await m.UsersApi(e).getDistinctPlatforms_ByUserId(u)).platforms, { data: n };
      } catch (t) {
        return s = f.getErrorType(t), { error: s };
      } finally {
        r({ linkedPlatform: n, linkedPlatformError: s, linkedPlatformFetchStatus: a.IDLE });
      }
    },
    [e]
  ), T = o(
    async (u, n, s) => {
      let t = null, l = null;
      try {
        return r({ linkAccountError: l, linkAccountFetchStatus: a.FETCHING }), await m.UsersApi(e).postUserMePlatform_ByPlatformId(u, { ticket: n, redirectUri: s }), { data: null };
      } catch (c) {
        if (V.isAxiosError(c) && c.response) {
          const p = ft.safeParse(c.response.data);
          c.response.status === 409 && c.response.data && p.success && p.data.messageVariables.publisherAccounts.length > 1 && (t = {
            platformId: u,
            conflictAccountsData: p.data.messageVariables
          });
        }
        return l = f.getErrorType(c), { error: l };
      } finally {
        r({ accountConflictInformation: t, linkAccountError: l, linkAccountFetchStatus: a.IDLE });
      }
    },
    [e]
  ), R = o(
    async (u) => {
      let n = null;
      try {
        return r({ unlinkAccountError: n, unlinkAccountFetchStatus: a.FETCHING }), await m.UsersApi(e).deleteAllMeUser_ByPlatformId(u), { data: null };
      } catch (s) {
        return n = f.getErrorType(s), { error: n };
      } finally {
        r({ unlinkAccountError: n, unlinkAccountFetchStatus: a.IDLE });
      }
    },
    [e]
  ), g = o(
    async (u) => {
      let n = null, s = null;
      try {
        r({ requestStatusError: s, requestStatusFetchStatus: a.FETCHING });
        const t = await m.UsersApi(e).getAsyncStatus_ByRequestId(u);
        if (t.status === M.enum.FAILED && t.error && t.error.errorCode === $ && (!t.error.messageVariables || !t.error.messageVariables.publisherAccounts))
          return n = {
            platformId: t.payload.platformId,
            conflictAccountsData: null,
            previousLinkedPlatformAccount: t.error.previousLinkedPlatformAccount,
            errorCode: t.error.errorCode
          }, { data: t };
        if (t.status === M.enum.FAILED && t.error && (!t.error.messageVariables || !t.error.messageVariables.publisherAccounts))
          throw t.error;
        return t.status === M.enum.FAILED && t.error && t.error.messageVariables && t.error.messageVariables.publisherAccounts ? (n = {
          platformId: t.payload.platformId,
          conflictAccountsData: t.error.messageVariables,
          previousLinkedPlatformAccount: void 0,
          errorCode: t.error.errorCode
        }, { data: t }) : { data: t };
      } catch (t) {
        return s = f.getErrorType(t), { error: s };
      } finally {
        r({ accountConflictInformation: n, requestStatusError: s, requestStatusFetchStatus: a.IDLE });
      }
    },
    [e]
  ), E = o(
    async (u, n) => {
      let s = null;
      try {
        return r({ linkedPlatformError: s, linkedPlatformFetchStatus: a.FETCHING }), { data: (await m.UsersApi(e).getPlatforms_ByUserId(u)).data.find((c) => c.platformId === n) };
      } catch (t) {
        return s = f.getErrorType(t), { error: s };
      } finally {
        r({ linkedPlatformError: s, linkedPlatformFetchStatus: a.IDLE });
      }
    },
    [e]
  ), A = o(
    async (u, n) => {
      var s, t, l;
      try {
        const c = await E(u, n);
        (s = c.data) == null || delete s.displayName, (t = c.data) == null || delete t.emailAddress, (l = c.data) == null || delete l.platformUserId;
        const p = {
          [n]: c
        }, _ = await dt.UserProfileApi(e).updateProfileCustomAttribute_ByUserId(u, p), C = c || _;
        if (C)
          throw C;
        return { data: null };
      } catch (c) {
        return { error: c };
      }
    },
    [e]
  ), h = o(
    async ({
      email: u,
      password: n,
      linkingToken: s,
      clientId: t,
      onTokenExpired: l,
      onErrorLinkDeletion: c,
      onErrorUserBanned: p,
      onRequired2FA: _
    }) => {
      const C = {
        password: n,
        linkingToken: s,
        username: u,
        client_id: t
      };
      let i = null;
      try {
        return r({ linkAccountError: i, linkAccountFetchStatus: a.FETCHING }), { data: await m.OAuth20ExtensionApi(e).postAuthenticateWithLink(C) };
      } catch (S) {
        const k = V.isAxiosError(S) && S.response, G = V.extractServiceErrorCode(S);
        if (G === Y && l)
          return l(), { data: null };
        if (G === J && c)
          return c(), { data: null };
        if (G === tt && p)
          return p(), { data: null };
        const I = k ? X.getMfaDataFromError(k) : null;
        return I && _ ? (_(I), { data: null }) : (i = f.getErrorType(S), { error: i });
      } finally {
        r({ linkAccountError: i, linkAccountFetchStatus: a.IDLE });
      }
    },
    [e]
  ), F = o(
    async ({
      linkingToken: u,
      clientId: n,
      userAccountParams: s,
      refreshSession: t
    }) => {
      const l = {
        username: s.username,
        password: s.password || null,
        linkingToken: u,
        client_id: n
      };
      let c = null;
      try {
        r({ linkAccountError: c, linkAccountFetchStatus: a.FETCHING }), await m.UsersV4Api(e).createUser(s);
        const p = await m.OAuth20ExtensionApi(e).postAuthenticateWithLink(l);
        return t && t(p.access_token, p.refresh_token), { data: p };
      } catch (p) {
        return c = f.getErrorType(p), { error: c };
      } finally {
        r({ linkAccountError: c, linkAccountFetchStatus: a.IDLE });
      }
    },
    [e]
  ), N = o(
    async (u, n) => {
      let s = null;
      try {
        r({ upgradeHeadlessAccountError: s, upgradeHeadlessAccountFetchStatus: a.FETCHING });
        const t = lt.safeParse(u), l = ct.safeParse(u);
        if (t.success && n)
          return { data: await m.UsersApi(e).createUserMeHeadlesCodeVerify(t.data) };
        if (l.success)
          return { data: await m.UsersV4Api(e).createUserMeHeadlesCodeVerify(l.data) };
        throw new Error("invalid params type");
      } catch (t) {
        return s = f.getErrorType(t), { error: s };
      } finally {
        r({ upgradeHeadlessAccountError: s, upgradeHeadlessAccountFetchStatus: a.IDLE });
      }
    },
    [e]
  );
  return {
    state: d,
    mutations: {
      resetState: D,
      resetErrorState: L,
      getUserDistinctLinkedPlatform: y,
      linkAccount: T,
      unLinkAccount: R,
      requestStatus: g,
      getLinkedAccountByPlatformId: E,
      linkExistingAccount: h,
      linkNewPlatformAccount: F,
      upgradeHeadlessAccount: N,
      updateUserCustomAttribute: A
    }
  };
}
function Nt() {
  var p, _, C;
  const e = v(b.isDesktopApp() ? new At(Device.desktopStorage) : null), [d] = O(), { state: r, mutations: D } = rt(), { mutations: L } = pt(), { state: y, mutations: T } = St(), { mutations: R } = ht(), { state: g } = nt(), { state: E } = et(), { state: A } = st(), h = o(
    (i, S) => {
      e.current && (S && i && (e.current.set(U.ACCESS_TOKEN, i), e.current.set(U.REFRESH_TOKEN, S)), d.refreshTokens(i, S));
    },
    [d]
  ), F = v(r), N = v(y);
  K(() => {
    F.current = r;
  }, [r]), K(() => {
    N.current = y;
  }, [y]);
  const u = o((i) => {
    if (!b.isDesktopApp()) {
      const { deletionMark: S } = N.current, { user: k } = F.current;
      k && !S && i && i(), S && t();
    }
    b.isDesktopApp() && (n(), h(void 0, void 0), i && i());
  }, []), n = o(() => {
    if (D.resetState(), L.resetState(), T.resetState(), R.resetState(), !!e.current)
      for (const i of Object.keys(U))
        i !== U.SETTINGS && e.current.delete(i);
  }, [D]), s = o(async () => {
    const i = await new X(d).refreshToken();
    if (!i)
      return n(), null;
    const S = ut.safeParse(i);
    return S.success ? S.data : null;
  }, [d]), t = o(
    async (i) => {
      b.isDesktopApp(), b.isDesktopApp() || (await D.logout(), n(), A.replace(i || E.home.link));
    },
    [A]
  ), l = o(async () => {
    var S;
    if (!d)
      return;
    const i = (S = g.flags) == null ? void 0 : S.isLegalEnabled;
    try {
      const [k, G] = await Promise.allSettled([
        D.fetchCurrentUserInformation(),
        L.fetchUnsignedPolicies()
      ]), I = k.status === "fulfilled" && k.value.data || null;
      if (it.currentUserIsEligible(I)) {
        const q = G.status === "fulfilled" ? G.value.data : null, Z = (q == null ? void 0 : q.length) === 0;
        (!i && !q || Z) && (I != null && I.userId) && (await T.fetchGdprDeletionStatus(I == null ? void 0 : I.userId), await D.fetchUserProfile(!0));
      }
    } catch (k) {
      console.error(k);
    }
  }, [d, (p = g.flags) == null ? void 0 : p.isLegalEnabled]), c = o(async () => {
    await l(), b.isDesktopApp();
  }, [l]);
  return {
    tokens: {
      accessToken: (_ = e.current) == null ? void 0 : _.get(U.ACCESS_TOKEN),
      refreshToken: (C = e.current) == null ? void 0 : C.get(U.REFRESH_TOKEN)
    },
    refreshSession: h,
    clearSession: u,
    refreshToken: s,
    logout: t,
    fetchAllUserInformation: l,
    refreshUser: c,
    clear: n
  };
}
export {
  Nt as a,
  ht as b,
  St as c,
  pt as u
};
