import { ErrorHelper as h } from "./accelbyte-widgets120.mjs";
import { Platform as o, OrderStatus as p } from "@accelbyte/sdk-platform";
import { Container as f } from "unstated";
const l = class extends f {
  constructor(t, r) {
    super(), this.sdk = t, this.cancelAll = async () => {
      const { pendingOrders: s } = this.state;
      if (s)
        try {
          const { userId: a } = this.props;
          await this.setState({ isCancelling: !0, cancellationError: null });
          const c = [], n = [];
          if (await Promise.all(
            s.map(async (e) => {
              const { orderNo: d } = e;
              try {
                const i = await o.OrderApi(this.sdk).updateCancel_ByUserId_ByOrderNo(a, d);
                return c.push(i);
              } catch (i) {
                return n.push({ order: e, error: i });
              }
            })
          ), n.length > 0 && s.length === n.length) {
            const e = n[0];
            if (e)
              throw e.error;
          }
        } catch (a) {
          console.error(a), await this.setState({ cancellationError: a });
        } finally {
          await this.setState({ isCancelling: !1 });
        }
    }, this.props = r, this.state = l.DEFAULT_STATE;
  }
  async init() {
    try {
      if (this.state.isFetchingOrders)
        return;
      await this.setState({
        isFetchingOrders: !0,
        pendingOrders: null,
        fetchOrdersError: null
      });
      const t = await this.fetchPendingOrders();
      if (await this.setState({
        pendingOrders: t
      }), t.length > 0 && t[0].paymentOrderNo) {
        const r = await this.fetchPaymentInfo(t[0].paymentOrderNo);
        await this.setState({
          paymentInfo: r
        });
      }
    } catch (t) {
      await this.setState({ fetchOrdersError: t });
    } finally {
      await this.setState({ isFetchingOrders: !1 });
    }
  }
  async fetchPendingOrders() {
    const { userId: t, itemId: r } = this.props;
    return (await o.OrderApi(this.sdk).getOrders_ByUserId(t, {
      itemId: r,
      status: p.enum.INIT
    })).data;
  }
  async fetchPaymentInfo(t) {
    try {
      return await o.PaymentStationApi(this.sdk).getInfoPayment_ByPaymentOrderNo(t);
    } catch (r) {
      if (h.isAxiosError(r) && r.response && r.response.status === 404)
        return null;
      throw r;
    }
  }
};
let u = l;
u.DEFAULT_STATE = {
  isFetchingOrders: !1,
  pendingOrders: null,
  paymentInfo: null,
  fetchOrdersError: null,
  isCancelling: !1,
  cancellationError: null
};
export {
  u as PendingOrdersAppManager
};
