import { I as R, C as P } from "./EcommTypes-beac1085.mjs";
import { R as F, P as L } from "./usePendingOrders-515ff6cf.mjs";
import { Platform as E, PlatformClient as V } from "@accelbyte/sdk-platform";
import { F as i, u as O, E as b, W as A, b as H } from "./Env-92498313.mjs";
import { c as g, u as U } from "./useRoutes-367960a3.mjs";
import { useCallback as d } from "react";
var B = /* @__PURE__ */ ((e) => (e.NAME = "name", e.NAME_ASC = "name:asc", e.NAME_DESC = "name:desc", e.CREATED_AT = "createdAt", e.CREATED_AT_ASC = "createdAt:asc", e.CREATED_AT_DESC = "createdAt:desc", e.UPDATED_AT = "updatedAt", e.UPDATED_AT_ASC = "updatedAt:asc", e.UPDATED_AT_DESC = "updatedAt:desc", e.DISPLAY_ORDER = "displayOrder", e.DISPLAY_ORDER_ASC = "displayOrder:asc", e.DISPLAY_ORDER_DESC = "displayOrder:desc", e))(B || {});
const N = {
  wallet: null,
  walletFetchStatus: i.IDLE,
  walletError: null,
  coins: null,
  coinsFetchStatus: i.IDLE,
  coinsError: null
}, T = 50, k = g("wallet", N);
function v() {
  const [e] = O(), [n, r] = U(k), c = d(
    async (l, a) => {
      var o;
      if (!a)
        return null;
      let t = null, s = null;
      try {
        return r({
          walletFetchStatus: i.FETCHING,
          walletError: null
        }), t = await E.WalletApi(e).getWallet_ByUserId_ByCurrencyCode(l, a), { data: t };
      } catch (p) {
        return b.isAxiosError(p) && ((o = p.response) == null ? void 0 : o.status) === 404 ? null : (s = A.getErrorType(p), { error: s });
      } finally {
        r({ wallet: t, walletError: s, walletFetchStatus: i.IDLE });
      }
    },
    [e]
  ), u = d(
    (l, a) => {
      if (!(!l || !(a != null && a.isVirtualCurrencyVisible)))
        return c(l.userId, H.WALLET_VIRTUAL_CURRENCY_CODE);
    },
    [e]
  ), f = d(
    async (l, a) => {
      if (!l || !a)
        return;
      let t = null, s = null;
      try {
        return r({
          coinsFetchStatus: i.FETCHING,
          coinsError: null
        }), t = await M(e, l, a), { data: t };
      } catch (o) {
        return s = A.getErrorType(o), { error: o };
      } finally {
        r({ coins: t, coinsError: s, coinsFetchStatus: i.IDLE });
      }
    },
    [e]
  ), h = d(
    async (l, a, t, s) => {
      if (!l)
        return;
      let o = null;
      try {
        return r({ coinsFetchStatus: i.UPDATING }), await E.OrderApi(e).createOrder_ByUserId(l.userId, {
          itemId: a.itemId,
          quantity: 1,
          price: t.price || 0,
          discountedPrice: F.getFinalPrice(t),
          currencyCode: t.currencyCode,
          // returnUrl: `${location.protocol}//${location.host}${Env.PLAYER_PORTAL_BASE_URL}`
          returnUrl: s
        }), { data: null };
      } catch (p) {
        return o = A.getErrorType(p), { error: p };
      } finally {
        r({ coinsError: o, coinsFetchStatus: i.IDLE });
      }
    },
    [e]
  ), I = d(() => {
    r(N);
  }, []);
  return {
    state: n,
    mutations: {
      fetchWallet: c,
      fetchCoinsList: f,
      purchaseCoin: h,
      refreshWallet: u,
      resetState: I
    }
  };
}
async function M(e, n, r) {
  if (!n)
    return null;
  let c = [], u = !0, f = 0;
  try {
    for (; u; ) {
      let h;
      try {
        h = await E.ItemApi(e).getItemsByCriteria({
          itemType: R.enum.COINS,
          region: n.country,
          limit: T,
          sortBy: [B.DISPLAY_ORDER_ASC],
          offset: f
        });
      } catch (t) {
        throw u = !1, t;
      }
      const { data: I, paging: l } = h;
      u = Boolean(l && l.next);
      const a = I.filter((t) => {
        const { targetCurrencyCode: s } = t;
        if (!s)
          return !1;
        const o = r.get(s);
        return o && o.currencyType === P.enum.VIRTUAL && !!t.useCount && L.makePaymentOptionList(t.regionData || [], r).length > 0;
      });
      c = c.concat(a), f += T;
    }
  } catch (h) {
    console.error(h);
  }
  return c;
}
const W = {
  // We don't store the "created order" here because it's only used once and we can return it right away from the purchase function.,
  purchaseProcessFetchStatus: i.IDLE,
  purchaseProcessError: null,
  prepurchaseInformation: null,
  prepurchaseInformationFetchStatus: i.IDLE,
  prepurchaseInformationError: null
}, G = g("orders-process", W);
function re() {
  const [e] = O(), [n, r] = U(G), {
    mutations: { refreshWallet: c }
  } = v(), u = d(() => {
    r(W);
  }, []), f = d(
    async ({
      item: a,
      userId: t,
      currencyMap: s
    }) => {
      let o = null, p = null;
      try {
        r({
          prepurchaseInformationFetchStatus: i.FETCHING,
          prepurchaseInformationError: null
        });
        const { availableItemInfo: m, itemOwnership: y, baseAppOwnership: C, purchaseConditionValidation: S } = await Y({
          sdk: e,
          userId: t,
          item: a
        }), w = await z(e, t, q(a, s)), x = L.makePurchaseConstraint(a, m, s, w);
        let D = null;
        const _ = $(S);
        return _ && (D = await j(e, _)), o = {
          walletMap: w,
          purchaseConstraint: x,
          availableItemInfo: m,
          itemOwnership: y,
          baseAppOwnership: C,
          purchaseConditionValidation: S,
          unmatchedPurchaseRequirementItems: D
        }, { data: o };
      } catch (m) {
        return p = A.getErrorType(m), { error: m };
      } finally {
        r({
          prepurchaseInformation: o,
          prepurchaseInformationFetchStatus: i.IDLE,
          prepurchaseInformationError: p
        });
      }
    },
    [e]
  ), h = d(
    async ({
      userId: a,
      item: t,
      regionData: s,
      quantity: o,
      returnUrl: p
    }) => {
      let m = null, y = null;
      if (!a)
        return { data: m };
      try {
        return r({
          purchaseProcessFetchStatus: i.PURCHASING,
          purchaseProcessError: null
        }), m = await E.OrderApi(e).createOrder_ByUserId(a, {
          quantity: o,
          price: (s.price || 0) * o,
          discountedPrice: F.getFinalPrice(s) * o,
          currencyCode: s.currencyCode,
          itemId: t.itemId,
          returnUrl: p
        }), { data: m };
      } catch (C) {
        return y = A.getErrorType(C), { error: C };
      } finally {
        r({
          purchaseProcessFetchStatus: i.IDLE,
          purchaseProcessError: y
        });
      }
    },
    [e]
  ), I = d(
    ({ user: a, flags: t, createdOrder: s }) => {
      if (s.itemSnapshot)
        switch (s.currency.currencyType) {
          case P.enum.VIRTUAL:
            c(a, t);
            break;
        }
    },
    []
  ), l = d(
    ({ user: a, flags: t, createdOrder: s }) => {
      if (s.itemSnapshot)
        switch (s.itemSnapshot.itemType) {
          case R.enum.COINS:
            c(a, t);
            break;
        }
    },
    []
  );
  return {
    state: n,
    mutations: {
      resetState: u,
      prepareOrderProcess: f,
      purchase: h,
      onOrderCreatedHook: I,
      onOrderFulfilledHook: l
    }
  };
}
async function Y({ sdk: e, userId: n, item: r }) {
  const [c, u, f, h] = await Promise.all([
    E.ItemApi(e).getDynamic_ByItemId(r.itemId),
    n && r.itemId ? E.EntitlementApi(e).getEntitlementsOwnershipAny_ByUserId(n, {
      itemIds: [r.itemId].filter(Boolean)
    }) : null,
    n && r.baseAppId ? E.EntitlementApi(e).getEntitlementsOwnershipAny_ByUserId(n, {
      appIds: [r.baseAppId].filter(Boolean)
    }) : null,
    n ? E.ItemApi(e).createItemPurchaseConditionValidate({
      itemIds: [r.itemId]
    }) : null
  ]);
  return {
    availableItemInfo: c,
    itemOwnership: u || null,
    baseAppOwnership: f || null,
    purchaseConditionValidation: h || null
  };
}
function $(e) {
  var c;
  if (!e || !e[0])
    return;
  const [{ validateDetails: n }] = e;
  if (!n || !((c = n[0]) != null && c.predicateValidateResults))
    return;
  const r = [];
  return n[0].predicateValidateResults.forEach(({ unmatched: u }) => {
    u && r.push(...u);
  }), Array.from(new Set(r));
}
async function j(e, n) {
  return n.length === 0 ? null : await E.ItemApi(e).getItemsLocaleByIds({
    itemIds: n.toString()
  });
}
function q(e, n) {
  const r = new Set(
    Array.from(n.values()).filter((c) => c.currencyType === P.enum.VIRTUAL).map((c) => c.currencyCode)
  );
  return (e.regionData || []).map((c) => c.currencyCode).filter((c) => r.has(c));
}
async function z(e, n, r) {
  return n ? await V.getWalletMap(n, r, e) : /* @__PURE__ */ new Map();
}
export {
  B as I,
  re as a,
  v as u
};
