import { EligibleUser as f, Iam as m } from "@accelbyte/sdk-iam";
import { Container as h } from "unstated";
import { Basic as p } from "@accelbyte/sdk-basic";
const c = {
  isFetchingNamespaces: !1,
  platformUserInfo: [],
  fetchingNamespacesError: null,
  isLinkingConflictAccount: !1,
  linkingConflictAccountError: null
};
class A extends h {
  constructor(o) {
    super(), this.sdk = o, this.fetchNamespaceDisplayName = async (s) => {
      if (!this.state.isFetchingNamespaces)
        try {
          this.setState({ isFetchingNamespaces: !0, fetchingNamespacesError: null });
          const t = await p.NamespaceApi(this.sdk).getNamespaces(), e = this.getPlatformUserInfoWithNamespace(t, s);
          return this.setState({ platformUserInfo: e }), e;
        } catch (t) {
          throw this.setState({ fetchingNamespacesError: t }), t;
        } finally {
          this.setState({ isFetchingNamespaces: !1 });
        }
    }, this.getPlatformUserInfoWithNamespace = (s, t) => {
      const { publisherAccounts: e } = t;
      return e ? e.slice(0, 2).map((i) => {
        const n = i.linkedPlatforms.map((a) => {
          const r = s.find((l) => l.namespace === a.namespace);
          return {
            displayName: r ? r.displayName || "" : a.namespace,
            ...a
          };
        });
        return {
          ...i,
          linkedPlatforms: n
        };
      }) : [];
    }, this.linkConflictAccount = async (s, t, e) => {
      const { platformUserID: i } = e;
      if (this.state.isLinkingConflictAccount || !t || !f.safeParse(t).success)
        throw new Error("Linking conflict account or not elligible user");
      try {
        return this.setState({ isLinkingConflictAccount: !0, linkingConflictAccountError: null }), await m.UsersApi(this.sdk).createPlatformLink_ByUserId(t.userId, {
          platformId: s,
          platformUserId: i
        }), !0;
      } catch (n) {
        throw this.setState({ linkingConflictAccountError: n }), n;
      } finally {
        this.setState({ isLinkingConflictAccount: !1 });
      }
    }, this.state = c;
  }
  clear() {
    this.setState(c);
  }
}
export {
  A as LinkConflictAccountManager
};
