import { Ctx as o } from "./accelbyte-widgets33.mjs";
import { OrderAppManager as a } from "./accelbyte-widgets403.mjs";
import { Container as c } from "unstated";
import { EligibleUser as h } from "@accelbyte/sdk-iam";
import { Platform as n } from "@accelbyte/sdk-platform";
class I extends c {
  constructor(t) {
    super(), this.props = t, this.state = {
      codeItem: null,
      itemsInCode: [],
      baseApp: null,
      isFetching: !1,
      error: null,
      itemPublishingContent: null,
      itemPublishingContentError: null
    }, this.sdk = o.getAppState().getSdk();
  }
  setProperties(t) {
    for (const e in t)
      this.props[e] = t[e];
  }
  async init() {
    try {
      if (this.state.isFetching)
        return;
      this.setState({
        isFetching: !0,
        codeItem: null,
        itemsInCode: [],
        error: null
      });
      const t = await this.fetchBundleItem();
      await this.initPurchaseLogic(t);
      const e = await this.fetchItemsInCode(t.itemIds || []);
      let s = null;
      const { baseAppId: i } = t;
      i && (s = e.find((r) => i === r.appId) || await this.fetchBaseApp(i)), this.setState({
        codeItem: t,
        itemsInCode: e,
        baseApp: s,
        itemPublishingContent: null
      });
    } catch (t) {
      console.error(t), this.setState({ error: t });
    } finally {
      this.setState({ isFetching: !1 });
    }
  }
  async fetchBundleItem() {
    const { itemId: t, country: e, language: s } = this.props;
    return await n.ItemApi(this.sdk).getLocale_ByItemId(t, { language: s, region: e });
  }
  async fetchItemsInCode(t) {
    if (t.length === 0)
      return [];
    const { language: e, country: s } = this.props;
    return await n.ItemApi(this.sdk).getItemsLocaleByIds({
      language: e,
      itemIds: t.toString(),
      region: s
    });
  }
  async fetchBaseApp(t) {
    return await n.ItemApi(this.sdk).getItemsByAppId({
      appId: t,
      region: this.props.country,
      language: this.props.language
    });
  }
  async initPurchaseLogic(t) {
    const { user: e } = this.props, s = this.purchaseLogic = new a(this.sdk, {
      item: t,
      userId: h.safeParse(e).success && (e == null ? void 0 : e.userId) || null
    });
    s.subscribe(() => this.setState({})), await s.init();
    const { fetchError: i } = s.state;
    if (i)
      throw i;
  }
}
export {
  I as CodeItemDetailPageLogic
};
