import { CurrencyType as m } from "./accelbyte-widgets185.mjs";
import { PurchaseHelper as g } from "./accelbyte-widgets211.mjs";
import { RegionDataItemHelper as o } from "./accelbyte-widgets388.mjs";
import { PlatformClient as u, Platform as p } from "@accelbyte/sdk-platform";
import { Container as I } from "unstated";
import { PendingOrdersAppManager as d } from "./accelbyte-widgets451.mjs";
class M extends I {
  constructor(r, t) {
    super(), this.sdk = r, this.fetchPrepurchaseInformation = async () => {
      const { item: e, userId: i } = this.props, s = await u.fetchPrePurchaseInformation({
        userId: i,
        item: e,
        sdk: this.sdk
      });
      return {
        currencyMapResult: s.currencyMapResult,
        availableItemInfoResult: s.availableItemInfoResult,
        itemOwnershipResult: s.itemOwnershipResult,
        baseAppOwnershipResult: s.baseAppOwnershipResult,
        purchaseConditionValidationResult: s.purchaseConditionValidationResult
      };
    }, this.getPurchaseValidationUnmatchItemIds = (e) => {
      var n;
      if (!e || !e[0])
        return;
      const [{ validateDetails: i }] = e;
      if (!i || !((n = i[0]) != null && n.predicateValidateResults))
        return;
      const s = [];
      return i[0].predicateValidateResults.forEach(({ unmatched: a }) => {
        a && s.push(...a);
      }), Array.from(new Set(s));
    }, this.fetchPurchaseValidationUnmatchItem = (e) => {
      if (e != null && e.length)
        return p.ItemApi(this.sdk).getItemsLocaleByIds({ itemIds: e.toString() }).then((i) => {
          this.setState({ unmatchedPurchaseRequirementItems: i });
        }).catch((i) => {
          throw i;
        });
    }, this.isInitialized = !1, this.props = t, this.state = {
      activatedRegionData: null,
      isFetching: !1,
      isPurchasing: !1,
      createdOrder: null,
      walletMap: null,
      currencyMap: null,
      fetchError: null,
      purchaseError: null,
      availableItemInfo: null,
      purchaseConstraint: null,
      itemOwnership: null,
      baseAppOwnership: null,
      purchaseConditionValidation: null,
      unmatchedPurchaseRequirementItems: [],
      ...d.DEFAULT_STATE
    };
  }
  async fetchData() {
    try {
      if (this.state.isFetching)
        return;
      await this.setState({
        isFetching: !0,
        currencyMap: void 0,
        availableItemInfo: null,
        fetchError: null
      });
      const { item: r } = this.props, t = await this.fetchPrepurchaseInformation(), e = t.currencyMapResult, i = t.availableItemInfoResult;
      let s = t.itemOwnershipResult;
      const n = t.baseAppOwnershipResult, a = t.purchaseConditionValidationResult || void 0;
      await this.initPendingOrdersLogic();
      const c = await this.fetchWalletMap(this.filterUsedCurrencyCodesFromCurrencyMap(e));
      let l = [];
      r.flexible && (s = { owned: o.isOwned(r) }, s.owned && (l = o.buildRegionDataForOwnedFlexibleBundle(r)));
      const f = g.makePurchaseConstraint(
        r.flexible && (s != null && s.owned) ? { ...r, regionData: l } : r,
        i,
        e,
        c
      );
      await this.setState({
        walletMap: c,
        currencyMap: e,
        purchaseConstraint: f,
        availableItemInfo: i,
        itemOwnership: s,
        baseAppOwnership: n,
        purchaseConditionValidation: a
      });
      const h = this.getPurchaseValidationUnmatchItemIds(a);
      h && await this.fetchPurchaseValidationUnmatchItem(h);
    } catch (r) {
      await this.setState({ fetchError: r });
    } finally {
      await this.setState({ isFetching: !1 });
    }
  }
  init() {
    if (!this.isInitialized)
      return this.isInitialized = !0, this.fetchData();
  }
  async initPendingOrdersLogic() {
    const { item: r, userId: t } = this.props;
    if (!t)
      return;
    this.pendingOrdersLogic = new d(this.sdk, {
      userId: t,
      itemId: r.itemId
    }), this.pendingOrdersLogic.subscribe(() => {
      var i;
      this.setState({
        ...(i = this.pendingOrdersLogic) == null ? void 0 : i.state
      });
    }), await this.pendingOrdersLogic.init();
    const { fetchOrdersError: e } = this.pendingOrdersLogic.state;
    if (e)
      throw e;
  }
  async purchase({ regionData: r, quantity: t, returnUrl: e }) {
    const { isPurchasing: i, isFetching: s } = this.state, { item: n, userId: a } = this.props;
    if (!(!a || i || s))
      try {
        await this.setState({ isPurchasing: !0, purchaseError: null });
        const c = await p.OrderApi(this.sdk).createOrder_ByUserId(a, {
          quantity: t,
          price: (r.price || 0) * t,
          discountedPrice: o.getFinalPrice(r) * t,
          currencyCode: r.currencyCode,
          itemId: n.itemId,
          returnUrl: e
        });
        this.setState({ createdOrder: c });
      } catch (c) {
        this.setState({ purchaseError: c });
      } finally {
        this.setState({ isPurchasing: !1 });
      }
  }
  filterUsedCurrencyCodesFromCurrencyMap(r) {
    const t = new Set(
      Array.from(r.values()).filter((e) => e.currencyType === m.enum.VIRTUAL).map((e) => e.currencyCode)
    );
    return (this.props.item.regionData || []).map((e) => e.currencyCode).filter((e) => t.has(e));
  }
  async fetchWalletMap(r) {
    const { userId: t } = this.props;
    return t ? await u.getWalletMap(t, r, this.sdk) : /* @__PURE__ */ new Map();
  }
  checkCanUserPurchase() {
    const { userId: r } = this.props;
    if (!r)
      return !0;
    const { purchaseConditionValidation: t } = this.state;
    return t && t[0] && t[0].purchasable;
  }
}
export {
  M as OrderAppManager
};
