import { LinkingProgressStatus as n } from "./accelbyte-widgets239.mjs";
import { ErrorHelper as l } from "./accelbyte-widgets120.mjs";
import { ERROR_CODE_TOKEN_EXPIRED as y, ERROR_CODE_LINK_DELETION_ACCOUNT as I, ERROR_USER_BANNED as L, ERROR_LINK_ANOTHER_3RD_PARTY_ACCOUNT as A } from "@accelbyte/sdk";
import { Container as C } from "unstated";
import { z as u } from "zod";
import { ConflictedUserPlatformAccounts as U, Iam as i, IamUserAuthorizationClient as w, IamOAuthClient as P, UpgradeHeadlessAccountWithVerificationCodeRequestV3 as E, UpgradeHeadlessAccountWithVerificationCodeRequestV4 as b } from "@accelbyte/sdk-iam";
const V = u.object({
  errorCode: u.number(),
  errorMessage: u.string(),
  messageVariables: U
}), k = {
  isFetching: !1,
  isLinking: !1,
  isRequesting: !1,
  linkedPlatform: null,
  linkSuccess: !1,
  unlinkSuccess: !1,
  error: null,
  accountConflictInformation: null,
  upgradeHeadlessAccountError: null,
  isUpgradingHeadlessAccount: !1,
  isUpgradingHeadlessAccountSuccess: !1
};
class T extends C {
  constructor(s) {
    super(), this.sdk = s, this.linkExistingAccount = async ({
      email: t,
      password: e,
      linkingToken: r,
      clientId: a,
      onTokenExpired: f,
      onErrorLinkDeletion: d,
      onErrorUserBanned: h,
      onRequired2FA: m
    }) => {
      const S = {
        password: e,
        linkingToken: r,
        username: t,
        client_id: a
      };
      try {
        return await i.OAuth20ExtensionApi(this.sdk).postAuthenticateWithLink(S);
      } catch (o) {
        const p = l.isAxiosError(o) && o.response, c = l.extractServiceErrorCode(o);
        if (c === y && f)
          return f(), null;
        if (c === I && d)
          return d(), null;
        if (c === L && h)
          return h(), null;
        const g = p ? w.getMfaDataFromError(p) : null;
        if (g && m)
          return m(g), null;
        throw o;
      }
    }, this.exchageTwitchPlatformTokentoABToken = async (t, e, r) => {
      const a = this.sdk.assembly().config;
      return await P.exchangeTokenOauthByPlatformId(t, e, r, a);
    }, this.clearFetchingStatus = () => {
      this.setState({
        linkSuccess: !1,
        unlinkSuccess: !1,
        error: null
      });
    }, this.state = k;
  }
  async getUserDistinctLinkedPlatform(s) {
    if (!this.state.isFetching)
      try {
        this.setState({ isFetching: !this.state.linkedPlatform }), this.clearFetchingStatus();
        const t = await i.UsersApi(this.sdk).getDistinctPlatforms_ByUserId(s);
        return this.setState({ linkedPlatform: t.platforms }), t.platforms;
      } catch (t) {
        throw this.setState({ error: t }), t;
      } finally {
        this.setState({ isFetching: !1 });
      }
  }
  async linkAccount(s, t, e) {
    if (!this.state.isLinking)
      try {
        this.setState({ isLinking: !0 }), this.clearFetchingStatus(), await i.UsersApi(this.sdk).postUserMePlatform_ByPlatformId(s, { ticket: t, redirectUri: e }), this.setState({ linkSuccess: !0 });
      } catch (r) {
        throw r.response ? (l.isAxiosError(r) && r.response.status === 409 && r.response.data && V.safeParse(r.response.data).success && r.response.data.messageVariables.publisherAccounts.length > 1 && await this.setState({
          accountConflictInformation: {
            platformId: s,
            conflictAccountsData: r.response.data.messageVariables
          }
        }), r) : (this.setState({ error: r }), r);
      } finally {
        this.setState({ isLinking: !1 });
      }
  }
  async requestStatus(s) {
    if (!this.state.isLinking)
      try {
        this.setState({ isLinking: !0, accountConflictInformation: null }), this.clearFetchingStatus();
        const t = await i.UsersApi(this.sdk).getAsyncStatus_ByRequestId(s);
        if (t.status === n.enum.FAILED && t.error && t.error.errorCode === A && (!t.error.messageVariables || !t.error.messageVariables.publisherAccounts))
          return await this.setState({
            accountConflictInformation: {
              platformId: t.payload.platformId,
              conflictAccountsData: null,
              previousLinkedPlatformAccount: t.error.previousLinkedPlatformAccount,
              errorCode: t.error.errorCode
            }
          }), t;
        if (t.status === n.enum.FAILED && t.error && (!t.error.messageVariables || !t.error.messageVariables.publisherAccounts))
          throw t.error;
        return t.status === n.enum.FAILED && t.error && t.error.messageVariables && t.error.messageVariables.publisherAccounts && await this.setState({
          accountConflictInformation: {
            platformId: t.payload.platformId,
            conflictAccountsData: t.error.messageVariables,
            previousLinkedPlatformAccount: void 0,
            errorCode: t.error.errorCode
          }
        }), t;
      } catch (t) {
        throw this.setState({ error: t }), t;
      } finally {
        this.setState({ isLinking: !1 });
      }
  }
  async linkThirdPartyAccountByWeblink(s, t) {
    if (!this.state.isLinking)
      try {
        this.setState({ isLinking: !0, accountConflictInformation: null }), this.clearFetchingStatus();
        const e = await i.UsersApi(this.sdk).postWebLinkProcesMeUser_ByPlatformId(s, t);
        if (e.status === n.enum.FAILED && e.error && e.error.errorCode === A && (!e.error.messageVariables || !e.error.messageVariables.publisherAccounts))
          return await this.setState({
            accountConflictInformation: {
              platformId: e.payload.platformId,
              conflictAccountsData: null,
              previousLinkedPlatformAccount: e.error.previousLinkedPlatformAccount,
              errorCode: e.error.errorCode
            }
          }), e;
        if (e.status === n.enum.FAILED && e.error && (!e.error.messageVariables || !e.error.messageVariables.publisherAccounts))
          throw e.error;
        return e.status === n.enum.FAILED && e.error && e.error.messageVariables && e.error.messageVariables.publisherAccounts && await this.setState({
          accountConflictInformation: {
            platformId: e.payload.platformId,
            conflictAccountsData: e.error.messageVariables,
            previousLinkedPlatformAccount: void 0,
            errorCode: e.error.errorCode
          }
        }), e;
      } catch (e) {
        throw this.setState({ error: e }), e;
      } finally {
        this.setState({ isLinking: !1 });
      }
  }
  async getLinkedAccountByPlatformId(s, t) {
    return (await i.UsersApi(this.sdk).getPlatforms_ByUserId(s)).data.find((a) => a.platformId === t);
  }
  async unLinkAccount(s) {
    if (!this.state.isLinking)
      try {
        this.setState({ isLinking: !0 }), this.clearFetchingStatus(), await i.UsersApi(this.sdk).deleteAllMeUser_ByPlatformId(s), this.setState({ unlinkSuccess: !0 });
      } catch (t) {
        throw this.setState({ error: t }), t;
      } finally {
        this.setState({ isLinking: !1 });
      }
  }
  async getLinkedAccountByPlatformUserId(s, t) {
    return await i.UsersApi(this.sdk).getUser_ByPlatformId_ByPlatformUserId(s, t);
  }
  async linkNewPlatformAccount({
    linkingToken: s,
    clientId: t,
    userAccountParams: e,
    refreshSession: r
  }) {
    this.setState({ isLinking: !0, error: null });
    try {
      await i.UsersV4Api(this.sdk).createUser(e);
      const a = await i.OAuth20ExtensionApi(this.sdk).postAuthenticateWithLink({
        username: e.username,
        password: e.password || null,
        linkingToken: s,
        client_id: t
      });
      return r && r(a.access_token, a.refresh_token), this.setState({ linkSuccess: !0 }), a;
    } catch (a) {
      throw this.setState({ linkSuccess: !1, error: a }), a;
    } finally {
      this.setState({ isLinking: !1 });
    }
  }
  async upgradeHeadlessAccount(s, t) {
    if (!this.state.isLinking)
      try {
        this.setState({
          isUpgradingHeadlessAccount: !0,
          upgradeHeadlessAccountError: null
        });
        const e = E.safeParse(s), r = b.safeParse(s);
        if (e.success && t)
          await i.UsersApi(this.sdk).createUserMeHeadlesCodeVerify(e.data);
        else if (r.success)
          await i.UsersV4Api(this.sdk).createUserMeHeadlesCodeVerify(r.data);
        else
          throw new Error("invalid params type");
        this.setState({ isUpgradingHeadlessAccountSuccess: !0 });
      } catch (e) {
        throw this.setState({ isUpgradingHeadlessAccountSuccess: !1, upgradeHeadlessAccountError: e }), e;
      } finally {
        this.setState({ isUpgradingHeadlessAccount: !1 });
      }
  }
  clear() {
    this.setState(k);
  }
}
export {
  T as LinkedAccountsAppManager
};
