import { ErrorHelper as c } from "./accelbyte-widgets120.mjs";
import { TokenResponseV3 as d, IamUserAuthorizationClient as l, IamOAuthClient as g, Iam as o } from "@accelbyte/sdk-iam";
import { Container as p } from "unstated";
import { z as y } from "zod";
import { Basic as n } from "@accelbyte/sdk-basic";
import { Event as U } from "@accelbyte/sdk-event";
const u = y.enum(["NETWORK", "SERVER", "UNKNOWN"]), f = {
  user: null,
  errorFetchingUser: null,
  isFetchingUser: !1,
  isFetchingProfile: !1,
  userProfile: null,
  errorFetchingProfile: null,
  isUpdating: !1,
  updateError: null,
  isRequestingCode: !1,
  requestCodeError: null,
  isUpgradingHeadless: !1,
  upgradeHeadlessError: null,
  authenticatorKey: null,
  isLinkingAccount: !1,
  isFetchingHistory: !1,
  errorFetchingHistory: null,
  accountHistory: null,
  ageRestrictionError: null,
  ageRestriction: {
    age: 0,
    countryName: ""
  },
  currentCountryLocation: null
};
class C extends p {
  constructor(t) {
    super(), this.sdk = t, this.refreshToken = async () => {
      const e = await this.userAuthorizationClient.refreshToken();
      if (!e)
        return this.clear(), null;
      const r = d.safeParse(e);
      return r.success ? r.data : null;
    }, this.isSessionValid = () => !!this.state.user, this.state = {
      ...f,
      mfaData: l.getMfaDataFromStorage()
    }, this.oauthClient = new g(t), this.userAuthorizationClient = new l(t);
  }
  updateMFAData(t) {
    return this.setState({ mfaData: t || l.getMfaDataFromStorage() });
  }
  removeMFAData() {
    return l.removeMfaDataFromStorage(), this.setState({ mfaData: void 0 });
  }
  async logout() {
    await this.oauthClient.logout();
  }
  async revoke({ token: t }) {
    try {
      await this.oauthClient.revoke({ token: t });
    } finally {
      this.clear();
    }
  }
  async verify2FA(t) {
    const { mfaData: e } = this.state;
    return e ? (await this.oauthClient.verify2FA({ ...t, mfaToken: e.mfaToken })).data : void 0;
  }
  async request2FAEmailCode(t) {
    const { mfaData: e } = this.state;
    return e ? (await this.oauthClient.request2FAEmailCode({ ...t, mfaToken: e.mfaToken })).data : void 0;
  }
  getEmailUserFromMfaData() {
    const { mfaData: t } = this.state;
    if (t)
      return t.email;
  }
  async generateAuthenticatorSecretKey() {
    const t = await o.UsersV4Api(this.sdk).createUserMeMfaAuthenticatorKey();
    return this.setState({ authenticatorKey: t }), t;
  }
  clear() {
    this.setState(f);
  }
  async fetchCurrentUserInformation() {
    var t;
    if (!this.state.isFetchingUser)
      try {
        this.setState({ isFetchingUser: !0 });
        const e = await o.UsersApi(this.sdk).getUsersMe();
        return this.setState({ user: e, errorFetchingUser: null }), e;
      } catch (e) {
        let r = u.enum.UNKNOWN;
        if (c.isAxiosError(e)) {
          const s = ((t = e.response) == null ? void 0 : t.status) || -1;
          s === 401 ? r = void 0 : s >= 500 ? r = u.Enum.SERVER : e.response || (r = u.Enum.NETWORK), s !== 401 && console.error("UserState", r);
        }
        if (this.setState({ user: null, errorFetchingUser: r }), r)
          throw r;
        return;
      } finally {
        this.setState({ isFetchingUser: !1 });
      }
  }
  async fetchUserProfile() {
    let t = null, e = null;
    if (!this.state.isFetchingProfile)
      try {
        return this.setState({
          isFetchingProfile: !this.state.userProfile,
          errorFetchingProfile: null
        }), t = await n.UserProfileApi(this.sdk).getUsersMeProfiles(), t || void 0;
      } catch (r) {
        throw e = r, r;
      } finally {
        this.setState({ errorFetchingProfile: e, userProfile: t, isFetchingProfile: !1 });
      }
  }
  async fetchOrCreateUserProfile() {
    let t = this.state.userProfile, e = null;
    if (!this.state.isFetchingProfile)
      try {
        return this.setState({
          isFetchingProfile: !this.state.userProfile,
          errorFetchingProfile: null
        }), t = await n.UserProfileApi(this.sdk).getUsersMeProfiles(), t;
      } catch (r) {
        const s = r, i = s.response;
        if (c.isAxiosError(s) && i && i.status === 404 && i.data && Number(i.data.errorCode) === 11440)
          try {
            return t = await n.UserProfileApi(this.sdk).createUserMeProfile({}), t;
          } catch (a) {
            throw e = a, a;
          }
        else
          throw e = s, s;
      } finally {
        this.setState({ errorFetchingProfile: e, userProfile: t, isFetchingProfile: !1 });
      }
  }
  async updateUser(t) {
    let e = this.state.user, r = null;
    if (!(this.state.isUpdating || Object.keys(t).length === 0))
      try {
        return this.setState({
          isUpdating: !0,
          updateError: null
        }), e = await o.UsersApi(this.sdk).updateUserMe(t), this.setState({ user: e }), e;
      } catch (s) {
        throw r = s, this.setState({ updateError: r }), s;
      } finally {
        this.setState({ isUpdating: !1 });
      }
  }
  async updateUserProfile(t) {
    let e = this.state.userProfile, r = null;
    if (!(this.state.isUpdating || Object.keys(t).length === 0))
      try {
        return this.setState({
          isUpdating: !0,
          updateError: null
        }), e = await n.UserProfileApi(this.sdk).updateUserMeProfile(t), this.setState({ userProfile: e }), e;
      } catch (s) {
        throw r = s, this.setState({ updateError: r }), s;
      } finally {
        this.setState({ isUpdating: !1 });
      }
  }
  async uploadUserProfileImage(t) {
    let e = this.state.userProfile, r = null;
    if (!this.state.isUpdating)
      try {
        return this.setState({
          isUpdating: !0,
          updateError: null
        }), await n.UserProfileApi(this.sdk).updateUserMeProfile({ avatarUrl: t }), e = { ...e, avatarUrl: t }, e;
      } catch (s) {
        throw r = s, s;
      } finally {
        this.setState({ updateError: r, isUpdating: !1, userProfile: e });
      }
  }
  async updateEmail(t, e) {
    try {
      this.setState({
        isUpdating: !0,
        updateError: null
      }), await o.UsersV4Api(this.sdk).updateUserMeEmail({ code: t, emailAddress: e });
    } catch (r) {
      throw this.setState({ updateError: r }), r;
    } finally {
      this.setState({ isUpdating: !1 });
    }
  }
  async updatePassword(t, e, r) {
    if (!this.state.isUpdating)
      try {
        this.setState({ isUpdating: !0, updateError: null }), await o.UsersApi(this.sdk).updateUserMePassword({ oldPassword: t, newPassword: e, languageTag: r });
      } catch (s) {
        throw this.setState({ updateError: s }), s;
      } finally {
        this.setState({ isUpdating: !1 });
      }
  }
  async fetchAccountHistory({
    userId: t,
    type: e,
    startDate: r,
    endDate: s,
    offset: i,
    pageSize: h
  }) {
    if (!this.state.isFetchingHistory)
      try {
        this.setState({
          isFetchingHistory: !0,
          errorFetchingHistory: null
        });
        const a = await U.EventV2Api(this.sdk).getEdithistory_ByUserId(t, {
          type: e,
          startDate: r,
          endDate: s,
          offset: i,
          pageSize: h
        });
        return this.setState({ accountHistory: a }), a;
      } catch (a) {
        throw this.setState({ errorFetchingHistory: a }), a;
      } finally {
        this.setState({ isFetchingHistory: !1 });
      }
  }
  async getAgeRestrictionByCountry(t) {
    try {
      this.setState({ isUpdating: !0, updateError: null });
      const e = await o.UsersApi(this.sdk).getAgerestrictionCountry_ByCountryCode(t), { ageRestriction: r, countryName: s, enable: i } = e;
      return this.setState({ ageRestriction: { age: i ? r : 0, countryName: s }, isUpdating: !1 }), e;
    } catch (e) {
      throw this.setState({ ageRestrictionError: e, isUpdating: !1 }), e;
    }
  }
  async getCurrentLocationCountry() {
    this.setState({ isUpdating: !0, updateError: null });
    const t = await o.OAuth20ExtensionApi(this.sdk).getLocationCountry();
    return this.setState({ currentCountryLocation: t, isUpdating: !1 }), t;
  }
  async updateCustomAttributes(t, e) {
    return await n.UserProfileApi(this.sdk).updateProfileCustomAttribute_ByUserId(t, e), this.fetchUserProfile();
  }
}
export {
  C as UserAppManager,
  u as UserStateError
};
