import { C as p, I as g } from "./EcommTypes-beac1085.mjs";
import { isAfter as A, isBefore as x } from "date-fns";
import { F as y, u as w, W as m, E as b } from "./Env-92498313.mjs";
import { c as T, u as S } from "./useRoutes-367960a3.mjs";
import { useCallback as h } from "react";
import { Platform as E, OrderStatus as v } from "@accelbyte/sdk-platform";
class f {
  static isPurchasable(e, t = new Date()) {
    return !this.isExpired(e, t) && !this.isNotAvailableYet(e, t);
  }
  static isDiscounted(e, t = new Date()) {
    const { price: r, discountedPrice: c } = e;
    return r === c ? !1 : !this.isDiscountExpired(e, t) && !this.isDiscountNotAvailableYet(e, t);
  }
  static isExpired(e, t = new Date()) {
    return e.expireAt === void 0 || e.expireAt === null ? !1 : A(t, new Date(e.expireAt));
  }
  static isNotAvailableYet(e, t = new Date()) {
    return e.purchaseAt === void 0 || e.purchaseAt === null ? !1 : x(t, new Date(e.purchaseAt));
  }
  static isDiscountExpirable(e) {
    return e.discountExpireAt !== void 0;
  }
  static isDiscountNotAvailableYet(e, t = new Date()) {
    return e.discountPurchaseAt === void 0 || e.discountPurchaseAt === null ? !1 : x(t, new Date(e.discountPurchaseAt));
  }
  static isDiscountExpired(e, t = new Date()) {
    return e.discountExpireAt === void 0 || e.discountExpireAt === null ? !1 : A(t, new Date(e.discountExpireAt));
  }
  static hasMatchingCurrencyInMap(e, t) {
    return !!t.get(e.currencyCode);
  }
  static calculateDiscountPercentage(e) {
    const t = e.price || 0, r = e.discountedPrice || 0;
    return t === 0 ? 0 : Math.floor((t - r) / t * 100);
  }
  static isCurrencyTypeVirtual(e) {
    return e.currencyType === p.enum.VIRTUAL;
  }
  static getFinalPrice(e) {
    return this.isDiscounted(e) ? e.discountedPrice || 0 : e.price || 0;
  }
  static finalPriceIsFree(e) {
    return this.getFinalPrice(e) <= 0;
  }
  static getFirstFreeRegionDatum(e) {
    return e.find((t) => this.finalPriceIsFree(t)) || null;
  }
  static isFree(e) {
    return !!this.getFirstFreeRegionDatum(e);
  }
  static getEstimatedPriceMap(e) {
    return (e == null ? void 0 : e.reduce(
      (t, r) => t.set(`${r.currencyNamespace}_${r.currencyCode}`, r),
      /* @__PURE__ */ new Map()
    )) || /* @__PURE__ */ new Map();
  }
  static buildRegionDataWithEstimatedPrice(e, t) {
    var n;
    if (!e.flexible)
      return e;
    const { regionData: r, ...c } = e;
    return (t == null ? void 0 : t.size) !== (r == null ? void 0 : r.length) ? c : (t && (e.regionData = r == null ? void 0 : r.map((s) => {
      const i = t.get(`${s.currencyNamespace}_${s.currencyCode}`);
      return i ? {
        ...s,
        priceDetails: i.priceDetails
      } : {};
    }), e.regionData = (n = e.regionData) == null ? void 0 : n.map((s) => {
      var a;
      const i = t.get(`${s.currencyNamespace}_${s.currencyCode}`);
      if (i) {
        let { price: u, discountedPrice: l } = i;
        if (this.isOwned(e)) {
          const d = (a = i.priceDetails) == null ? void 0 : a.reduce(
            (C, P) => {
              const { price: I, discountedPrice: F } = C;
              return {
                price: I + P.price * (P.quantity || 1),
                discountedPrice: F + P.discountedPrice * (100 - ((s == null ? void 0 : s.discountPercentage) || 0)) * (P.quantity || 1)
              };
            },
            { price: 0, discountedPrice: 0 }
          );
          d && (u = d.price, l = d.discountedPrice / 100);
        }
        return {
          ...s,
          price: u,
          discountedPrice: l
        };
      }
      return {};
    })), e);
  }
  // Build price and discountedPrice for owned flexible bundle is for display only
  static buildRegionDataForOwnedFlexibleBundle(e) {
    var t;
    return e.flexible ? ((t = e.regionData) == null ? void 0 : t.map((r) => {
      const { priceDetails: c } = r;
      if (c) {
        const { price: n, discountedPrice: s } = c.reduce(
          (i, a) => {
            const { price: u, discountedPrice: l } = i;
            return {
              price: (u + a.price) * (a.quantity || 1),
              discountedPrice: l + a.discountedPrice * (100 - ((r == null ? void 0 : r.discountPercentage) || 0)) * (a.quantity || 1)
            };
          },
          { price: 0, discountedPrice: 0 }
        );
        return {
          ...r,
          price: n,
          discountedPrice: s / 100
        };
      }
      return r;
    })) || [] : e.regionData || [];
  }
  // To check flexible bundle
  static isOwned(e) {
    const { flexible: t, regionData: r } = e;
    return !!t && (r == null ? void 0 : r.filter((c) => {
      const { priceDetails: n } = c;
      return n == null ? void 0 : n.some((s) => !s.owned);
    }).length) === 0;
  }
  static getCurrentRegionData(e, t) {
    var r;
    return ((r = e.regionData) == null ? void 0 : r.filter((c) => c.currencyCode === t || !e.flexible)) || [];
  }
}
class _ {
  static entitlementConstraintUnavailableForPurchase(e) {
    return e.maxAllowedPurchase <= 0;
  }
  static purchaseUnavailable(e) {
    return e ? this.entitlementConstraintUnavailableForPurchase(e.entitlementConstraint) : !1;
  }
  static getMaxPurchaseByWallet(e, t) {
    switch (e.currencyType) {
      case p.enum.REAL:
        return 1 / 0;
      case p.enum.VIRTUAL:
        return t ? Math.floor(t.balance / e.finalPrice) : 0;
      default:
        return 0;
    }
  }
  static itemIsFree(e) {
    return !!e.regionData;
  }
  static makePaymentOption(e, t) {
    const r = t.get(e.currencyCode);
    if (!r)
      return null;
    const c = r.currencyType, n = r.currencySymbol || r.currencyCode, s = this.calculateIntegerPrice(f.getFinalPrice(e), r), i = this.calculateIntegerPrice(e.price || 0, r), a = r.decimals;
    return {
      currencyType: c,
      currencySymbol: n,
      finalPrice: s,
      originalPrice: i,
      decimals: a,
      regionData: e
    };
  }
  static makePaymentOptionList(e, t) {
    if (!t)
      return [];
    const r = e.filter(
      (n) => f.isPurchasable(n) && f.hasMatchingCurrencyInMap(n, t)
    ).map((n) => this.makePaymentOption(n, t)).filter((n) => n !== null);
    return [
      ...r.filter((n) => (n == null ? void 0 : n.currencyType) === p.enum.REAL),
      ...r.filter((n) => (n == null ? void 0 : n.currencyType) === p.enum.VIRTUAL)
    ];
  }
  static makeWalletConstraint(e, t) {
    const r = t.get(e.regionData.currencyCode) || null;
    return {
      wallet: r,
      maxPurchase: this.getMaxPurchaseByWallet(e, r)
    };
  }
  static makePaymentOptionWithExpiryDiscount(e, t) {
    return this.makePaymentOptionList(e, t).filter(
      (r) => f.isDiscountExpirable(r.regionData) && f.isDiscounted(r.regionData)
    );
  }
  // Platform service treats -1 as Infinity for maxCount and maxCountPerUser
  // undefined is a possible value for maxCount and maxCountPerUser
  // PlayerPortal treats undefined as Infinity for maxCount and maxCountPerUser
  // Else return the value at minimum 0
  static convertMaxCountValue(e) {
    return e === void 0 || e === -1 ? 1 / 0 : Math.max(e, 0);
  }
  // Platform service treats -1 as Infinity for availableCountValue
  // undefined is a possible value for maxCount and maxCountPerUser
  // PlayerPortal treats undefined as Infinity for availableCountValue
  // Else return the value at minimum 0
  static convertAvailableCountValue(e) {
    return e === void 0 || e === -1 ? 1 / 0 : Math.max(e, 0);
  }
  static getMaxEntitlementsAllowed(e) {
    switch (e.itemType) {
      case g.enum.APP:
        return 1;
      default:
        return Math.min(this.convertMaxCountValue(e.maxCount), this.convertMaxCountValue(e.maxCountPerUser));
    }
  }
  static makePaymentEntitlementConstraint(e) {
    return {
      maxAllowedPurchase: this.convertAvailableCountValue(e.userPurchaseLimit)
    };
  }
  static makePurchaseConstraint(e, t, r, c) {
    return {
      paymentConstraints: this.makePaymentOptionList(e.regionData || [], r).map((n) => ({
        paymentOption: n,
        walletConstraint: this.makeWalletConstraint(n, c)
      })),
      entitlementConstraint: this.makePaymentEntitlementConstraint(t)
    };
  }
  static calculateIntegerPrice(e, t) {
    return e === null ? 0 : e / 10 ** t.decimals;
  }
}
const O = {
  pendingOrders: null,
  pendingOrdersFetchStatus: y.IDLE,
  pendingOrdersError: null,
  paymentInfo: null,
  paymentInfoFetchStatus: y.IDLE,
  paymentInfoError: null,
  cancelProcessFetchStatus: y.IDLE,
  cancelProcessError: null
}, D = T("pending-orders", O);
function H() {
  const [o] = w(), [e, t] = S(D), r = h(() => {
    t(O);
  }, []), c = h(
    async ({ itemId: i, userId: a }) => {
      let u = null, l = null;
      try {
        return t({
          pendingOrdersFetchStatus: y.FETCHING,
          pendingOrdersError: null
        }), u = await L({ sdk: o, itemId: i, userId: a }), { data: u };
      } catch (d) {
        return l = m.getErrorType(d), { error: d };
      } finally {
        t({
          pendingOrders: u,
          pendingOrdersFetchStatus: y.IDLE,
          pendingOrdersError: l
        });
      }
    },
    [o]
  ), n = h(
    async (i) => {
      if (!i.paymentOrderNo)
        return;
      let a = null, u = null;
      try {
        t({
          paymentInfoFetchStatus: y.FETCHING,
          paymentInfoError: null
        }), a = await N(o, i.paymentOrderNo);
      } catch (l) {
        u = m.getErrorType(l);
      } finally {
        t({
          paymentInfo: a,
          paymentInfoFetchStatus: y.IDLE,
          paymentInfoError: u
        });
      }
    },
    [o]
  ), s = h(
    async (i, a) => {
      let u = null;
      try {
        return t({
          cancelProcessFetchStatus: y.CANCELLING,
          cancelProcessError: null
        }), await Promise.all(
          i.map(async (l) => {
            const { orderNo: d } = l;
            return E.OrderApi(o).updateCancel_ByUserId_ByOrderNo(a, d);
          })
        ), t({ pendingOrders: null }), { data: !0 };
      } catch (l) {
        return u = m.getErrorType(l), { error: u };
      } finally {
        t({ cancelProcessError: u, cancelProcessFetchStatus: y.IDLE });
      }
    },
    [o, e.pendingOrders]
  );
  return {
    state: e,
    mutations: {
      fetchPendingOrders: c,
      fetchPaymentInfoFromOrder: n,
      cancelAllPendingOrders: s,
      resetState: r
    }
  };
}
async function L({
  sdk: o,
  userId: e,
  itemId: t
}) {
  return (await E.OrderApi(o).getOrders_ByUserId(e, { itemId: t, status: v.enum.INIT })).data;
}
async function N(o, e) {
  try {
    return await E.PaymentStationApi(o).getInfoPayment_ByPaymentOrderNo(e);
  } catch (t) {
    if (b.isAxiosError(t) && t.response && t.response.status === 404)
      return null;
    throw t;
  }
}
export {
  _ as P,
  f as R,
  H as u
};
