import { C as y, I as g } from "./FetchUtils-cc53dbb5.mjs";
import { isAfter as I, isBefore as E } from "date-fns";
import { F as c, e as O, u as x, f as F, W as h, E as C } from "./FetchConfigsUtils-476a602b.mjs";
import { useCallback as f } from "react";
import { Platform as P, OrderStatus as w } from "@accelbyte/sdk-platform";
class m {
  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: u } = e;
    return r === u ? !1 : !this.isDiscountExpired(e, t) && !this.isDiscountNotAvailableYet(e, t);
  }
  static isExpired(e, t = new Date()) {
    return e.expireAt === void 0 || e.expireAt === null ? !1 : I(t, new Date(e.expireAt));
  }
  static isNotAvailableYet(e, t = new Date()) {
    return e.purchaseAt === void 0 || e.purchaseAt === null ? !1 : E(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 : E(t, new Date(e.discountPurchaseAt));
  }
  static isDiscountExpired(e, t = new Date()) {
    return e.discountExpireAt === void 0 || e.discountExpireAt === null ? !1 : I(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 === y.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);
  }
}
class M {
  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 y.enum.REAL:
        return 1 / 0;
      case y.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 u = r.currencyType, n = r.currencySymbol || r.currencyCode, p = this.calculateIntegerPrice(m.getFinalPrice(e), r), l = this.calculateIntegerPrice(e.price || 0, r), o = r.decimals;
    return {
      currencyType: u,
      currencySymbol: n,
      finalPrice: p,
      originalPrice: l,
      decimals: o,
      regionData: e
    };
  }
  static makePaymentOptionList(e, t) {
    if (!t)
      return [];
    const r = e.filter(
      (n) => m.isPurchasable(n) && m.hasMatchingCurrencyInMap(n, t)
    ).map((n) => this.makePaymentOption(n, t)).filter((n) => n !== null);
    return [
      ...r.filter((n) => (n == null ? void 0 : n.currencyType) === y.enum.REAL),
      ...r.filter((n) => (n == null ? void 0 : n.currencyType) === y.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) => m.isDiscountExpirable(r.regionData) && m.isDiscounted(r.regionData)
    );
  }
  static convertMaxCountValue(e) {
    return e === void 0 || e === -1 ? 1 / 0 : Math.max(e, 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, u) {
    return {
      paymentConstraints: this.makePaymentOptionList(e.regionData || [], r).map((n) => ({
        paymentOption: n,
        walletConstraint: this.makeWalletConstraint(n, u)
      })),
      entitlementConstraint: this.makePaymentEntitlementConstraint(t)
    };
  }
  static calculateIntegerPrice(e, t) {
    return e === null ? 0 : e / 10 ** t.decimals;
  }
}
const A = {
  pendingOrders: null,
  pendingOrdersFetchStatus: c.IDLE,
  pendingOrdersError: null,
  paymentInfo: null,
  paymentInfoFetchStatus: c.IDLE,
  paymentInfoError: null,
  cancelProcessFetchStatus: c.IDLE,
  cancelProcessError: null
}, T = O(A);
function U() {
  const [s] = x(), [e, t] = F(T), r = f(() => {
    t(A);
  }, []), u = f(
    async ({ itemId: l, userId: o }) => {
      let i = null, a = null;
      try {
        return t({
          pendingOrdersFetchStatus: c.FETCHING,
          pendingOrdersError: null
        }), i = await S({ sdk: s, itemId: l, userId: o }), { data: i };
      } catch (d) {
        return a = h.getErrorType(d), { error: d };
      } finally {
        t({
          pendingOrders: i,
          pendingOrdersFetchStatus: c.IDLE,
          pendingOrdersError: a
        });
      }
    },
    [s]
  ), n = f(
    async (l) => {
      if (!l.paymentOrderNo)
        return;
      let o = null, i = null;
      try {
        t({
          paymentInfoFetchStatus: c.FETCHING,
          paymentInfoError: null
        }), o = await v(s, l.paymentOrderNo);
      } catch (a) {
        i = h.getErrorType(a);
      } finally {
        t({
          paymentInfo: o,
          paymentInfoFetchStatus: c.IDLE,
          paymentInfoError: i
        });
      }
    },
    [s]
  ), p = f(
    async (l, o) => {
      let i = null;
      try {
        return t({
          cancelProcessFetchStatus: c.CANCELLING,
          cancelProcessError: null
        }), await Promise.all(
          l.map(async (a) => {
            const { orderNo: d } = a;
            return P.OrderApi(s).updateCancel_ByUserId_ByOrderNo(o, d);
          })
        ), t({ pendingOrders: null }), { data: !0 };
      } catch (a) {
        return i = h.getErrorType(a), { error: i };
      } finally {
        t({ cancelProcessError: i, cancelProcessFetchStatus: c.IDLE });
      }
    },
    [s, e.pendingOrders]
  );
  return {
    state: e,
    mutations: {
      fetchPendingOrders: u,
      fetchPaymentInfoFromOrder: n,
      cancelAllPendingOrders: p,
      resetState: r
    }
  };
}
async function S({
  sdk: s,
  userId: e,
  itemId: t
}) {
  return (await P.OrderApi(s).getOrders_ByUserId(e, { itemId: t, status: w.enum.INIT })).data;
}
async function v(s, e) {
  try {
    return await P.PaymentStationApi(s).getInfoPayment_ByPaymentOrderNo(e);
  } catch (t) {
    if (C.isAxiosError(t) && t.response && t.response.status === 404)
      return null;
    throw t;
  }
}
export {
  M as P,
  m as R,
  U as u
};
