import { u as re } from "./stock-BSA86fOX.js";
import { a as K, O as oe, m as ae } from "./app-D3gm3Lsw.js";
import { ref as ie, computed as ce } from "vue";
import { c as le } from "./number-BfNWSAkN.js";
import { useCoreStore as he } from "@feedmepos/mf-common";
function ue() {
  return {
    stockBalance: {
      _id: "",
      items: []
    },
    productBalance: []
  };
}
const de = le(0), pe = {
  id: "",
  balance: de,
  closing: null,
  costs: null
}, I = ie(ue()), Be = () => {
  const e = K(), t = ce(() => {
    var r;
    const s = (r = I.value.stockBalance.skus) == null ? void 0 : r.groupBy((o) => o.id), i = (o) => {
      var l;
      return ((l = s == null ? void 0 : s.get(o)) == null ? void 0 : l[0]) ?? { ...pe, id: o };
    };
    return e.skus.map((o) => i(o._id));
  }), n = re();
  return {
    // state
    get stockBalance() {
      return {
        ...I.value.stockBalance,
        skus: t.value
      };
    },
    set stockBalance(s) {
      I.value.stockBalance = s;
    },
    get productBalance() {
      return I.value.productBalance;
    },
    set productBalance(s) {
      I.value.productBalance = s;
    },
    // actions
    async readStockBalance() {
      this.stockBalance = await n.readStockBalance();
    },
    async readProductBalance() {
      this.productBalance = [];
      const s = K(), i = oe({
        recipes: s.recipes,
        skus: s.skus,
        skuGroups: s.skuGroups,
        inventoryBindingMapping: {},
        stockBalance: this.stockBalance
        // silent: true
      });
      function r(o, l) {
        return Object.prototype.hasOwnProperty.call(o, l);
      }
      for (const o in i.convertCountdown)
        if (r(i.convertCountdown, o)) {
          const l = i.convertCountdown[o];
          this.productBalance.push({
            id: o,
            count: l
          });
        }
    }
  };
}, fe = ae((e, t) => ({
  getSubscribeUrl(n, s, i) {
    const r = new URLSearchParams({ clientId: n, type: s, ...i });
    return `${e.inventoryBackendUrl}/sse/subscribe?${r.toString()}`;
  },
  async getStatus(n, s) {
    const i = new URLSearchParams({ type: n, ...s }), r = `${e.inventoryBackendUrl}/sse/status?${i.toString()}`;
    return t.get(r);
  }
}));
class Q extends Error {
  constructor(t, n) {
    super(t), this.name = "ParseError", this.type = n.type, this.field = n.field, this.value = n.value, this.line = n.line;
  }
}
function F(e) {
}
function ve(e) {
  if (typeof e == "function")
    throw new TypeError(
      "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
    );
  const { onEvent: t = F, onError: n = F, onRetry: s = F, onComment: i } = e;
  let r = "", o = !0, l, f = "", v = "";
  function C(c) {
    const h = o ? c.replace(/^\xEF\xBB\xBF/, "") : c, [d, L] = Ee(`${r}${h}`);
    for (const x of d)
      _(x);
    r = L, o = !1;
  }
  function _(c) {
    if (c === "") {
      T();
      return;
    }
    if (c.startsWith(":")) {
      i && i(c.slice(c.startsWith(": ") ? 2 : 1));
      return;
    }
    const h = c.indexOf(":");
    if (h !== -1) {
      const d = c.slice(0, h), L = c[h + 1] === " " ? 2 : 1, x = c.slice(h + L);
      y(d, x, c);
      return;
    }
    y(c, "", c);
  }
  function y(c, h, d) {
    switch (c) {
      case "event":
        v = h;
        break;
      case "data":
        f = `${f}${h}
`;
        break;
      case "id":
        l = h.includes("\0") ? void 0 : h;
        break;
      case "retry":
        /^\d+$/.test(h) ? s(parseInt(h, 10)) : n(
          new Q(`Invalid \`retry\` value: "${h}"`, {
            type: "invalid-retry",
            value: h,
            line: d
          })
        );
        break;
      default:
        n(
          new Q(
            `Unknown field "${c.length > 20 ? `${c.slice(0, 20)}…` : c}"`,
            { type: "unknown-field", field: c, value: h, line: d }
          )
        );
        break;
    }
  }
  function T() {
    f.length > 0 && t({
      id: l,
      event: v || void 0,
      // If the data buffer's last character is a U+000A LINE FEED (LF) character,
      // then remove the last character from the data buffer.
      data: f.endsWith(`
`) ? f.slice(0, -1) : f
    }), l = void 0, f = "", v = "";
  }
  function m(c = {}) {
    r && c.consume && _(r), o = !0, l = void 0, f = "", v = "", r = "";
  }
  return { feed: C, reset: m };
}
function Ee(e) {
  const t = [];
  let n = "", s = 0;
  for (; s < e.length; ) {
    const i = e.indexOf("\r", s), r = e.indexOf(`
`, s);
    let o = -1;
    if (i !== -1 && r !== -1 ? o = Math.min(i, r) : i !== -1 ? i === e.length - 1 ? o = -1 : o = i : r !== -1 && (o = r), o === -1) {
      n = e.slice(s);
      break;
    } else {
      const l = e.slice(s, o);
      t.push(l), s = o + 1, e[s - 1] === "\r" && e[s] === `
` && s++;
    }
  }
  return [t, n];
}
class V extends Event {
  /**
   * Constructs a new `ErrorEvent` instance. This is typically not called directly,
   * but rather emitted by the `EventSource` object when an error occurs.
   *
   * @param type - The type of the event (should be "error")
   * @param errorEventInitDict - Optional properties to include in the error event
   */
  constructor(t, n) {
    var s, i;
    super(t), this.code = (s = n == null ? void 0 : n.code) != null ? s : void 0, this.message = (i = n == null ? void 0 : n.message) != null ? i : void 0;
  }
  /**
   * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
   * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
   * we explicitly include the properties in the `inspect` method.
   *
   * This is automatically called by Node.js when you `console.log` an instance of this class.
   *
   * @param _depth - The current depth
   * @param options - The options passed to `util.inspect`
   * @param inspect - The inspect function to use (prevents having to import it from `util`)
   * @returns A string representation of the error
   */
  [Symbol.for("nodejs.util.inspect.custom")](t, n, s) {
    return s(ee(this), n);
  }
  /**
   * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
   * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
   * we explicitly include the properties in the `inspect` method.
   *
   * This is automatically called by Deno when you `console.log` an instance of this class.
   *
   * @param inspect - The inspect function to use (prevents having to import it from `util`)
   * @param options - The options passed to `Deno.inspect`
   * @returns A string representation of the error
   */
  [Symbol.for("Deno.customInspect")](t, n) {
    return t(ee(this), n);
  }
}
function me(e) {
  const t = globalThis.DOMException;
  return typeof t == "function" ? new t(e, "SyntaxError") : new SyntaxError(e);
}
function G(e) {
  return e instanceof Error ? "errors" in e && Array.isArray(e.errors) ? e.errors.map(G).join(", ") : "cause" in e && e.cause instanceof Error ? `${e}: ${G(e.cause)}` : e.message : `${e}`;
}
function ee(e) {
  return {
    type: e.type,
    message: e.message,
    code: e.code,
    defaultPrevented: e.defaultPrevented,
    cancelable: e.cancelable,
    timeStamp: e.timeStamp
  };
}
var se = (e) => {
  throw TypeError(e);
}, H = (e, t, n) => t.has(e) || se("Cannot " + n), a = (e, t, n) => (H(e, t, "read from private field"), n ? n.call(e) : t.get(e)), p = (e, t, n) => t.has(e) ? se("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, n), u = (e, t, n, s) => (H(e, t, "write to private field"), t.set(e, n), n), w = (e, t, n) => (H(e, t, "access private method"), n), E, k, b, P, D, U, B, A, S, O, N, M, R, g, j, q, J, te, X, Y, W, Z, z;
class $ extends EventTarget {
  constructor(t, n) {
    var s, i;
    super(), p(this, g), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, p(this, E), p(this, k), p(this, b), p(this, P), p(this, D), p(this, U), p(this, B), p(this, A, null), p(this, S), p(this, O), p(this, N, null), p(this, M, null), p(this, R, null), p(this, q, async (r) => {
      var o;
      a(this, O).reset();
      const { body: l, redirected: f, status: v, headers: C } = r;
      if (v === 204) {
        w(this, g, W).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
        return;
      }
      if (f ? u(this, b, new URL(r.url)) : u(this, b, void 0), v !== 200) {
        w(this, g, W).call(this, `Non-200 status code (${v})`, v);
        return;
      }
      if (!(C.get("content-type") || "").startsWith("text/event-stream")) {
        w(this, g, W).call(this, 'Invalid content type, expected "text/event-stream"', v);
        return;
      }
      if (a(this, E) === this.CLOSED)
        return;
      u(this, E, this.OPEN);
      const _ = new Event("open");
      if ((o = a(this, R)) == null || o.call(this, _), this.dispatchEvent(_), typeof l != "object" || !l || !("getReader" in l)) {
        w(this, g, W).call(this, "Invalid response body, expected a web ReadableStream", v), this.close();
        return;
      }
      const y = new TextDecoder(), T = l.getReader();
      let m = !0;
      do {
        const { done: c, value: h } = await T.read();
        h && a(this, O).feed(y.decode(h, { stream: !c })), c && (m = !1, a(this, O).reset(), w(this, g, Z).call(this));
      } while (m);
    }), p(this, J, (r) => {
      u(this, S, void 0), !(r.name === "AbortError" || r.type === "aborted") && w(this, g, Z).call(this, G(r));
    }), p(this, X, (r) => {
      typeof r.id == "string" && u(this, A, r.id);
      const o = new MessageEvent(r.event || "message", {
        data: r.data,
        origin: a(this, b) ? a(this, b).origin : a(this, k).origin,
        lastEventId: r.id || ""
      });
      a(this, M) && (!r.event || r.event === "message") && a(this, M).call(this, o), this.dispatchEvent(o);
    }), p(this, Y, (r) => {
      u(this, U, r);
    }), p(this, z, () => {
      u(this, B, void 0), a(this, E) === this.CONNECTING && w(this, g, j).call(this);
    });
    try {
      if (t instanceof URL)
        u(this, k, t);
      else if (typeof t == "string")
        u(this, k, new URL(t, ge()));
      else
        throw new Error("Invalid URL");
    } catch {
      throw me("An invalid or illegal string was specified");
    }
    u(this, O, ve({
      onEvent: a(this, X),
      onRetry: a(this, Y)
    })), u(this, E, this.CONNECTING), u(this, U, 3e3), u(this, D, (s = n == null ? void 0 : n.fetch) != null ? s : globalThis.fetch), u(this, P, (i = n == null ? void 0 : n.withCredentials) != null ? i : !1), w(this, g, j).call(this);
  }
  /**
   * Returns the state of this EventSource object's connection. It can have the values described below.
   *
   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
   *
   * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
   * defined in the TypeScript `dom` library.
   *
   * @public
   */
  get readyState() {
    return a(this, E);
  }
  /**
   * Returns the URL providing the event stream.
   *
   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
   *
   * @public
   */
  get url() {
    return a(this, k).href;
  }
  /**
   * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
   *
   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
   */
  get withCredentials() {
    return a(this, P);
  }
  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
  get onerror() {
    return a(this, N);
  }
  set onerror(t) {
    u(this, N, t);
  }
  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
  get onmessage() {
    return a(this, M);
  }
  set onmessage(t) {
    u(this, M, t);
  }
  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
  get onopen() {
    return a(this, R);
  }
  set onopen(t) {
    u(this, R, t);
  }
  addEventListener(t, n, s) {
    const i = n;
    super.addEventListener(t, i, s);
  }
  removeEventListener(t, n, s) {
    const i = n;
    super.removeEventListener(t, i, s);
  }
  /**
   * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
   *
   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
   *
   * @public
   */
  close() {
    a(this, B) && clearTimeout(a(this, B)), a(this, E) !== this.CLOSED && (a(this, S) && a(this, S).abort(), u(this, E, this.CLOSED), u(this, S, void 0));
  }
}
E = /* @__PURE__ */ new WeakMap(), k = /* @__PURE__ */ new WeakMap(), b = /* @__PURE__ */ new WeakMap(), P = /* @__PURE__ */ new WeakMap(), D = /* @__PURE__ */ new WeakMap(), U = /* @__PURE__ */ new WeakMap(), B = /* @__PURE__ */ new WeakMap(), A = /* @__PURE__ */ new WeakMap(), S = /* @__PURE__ */ new WeakMap(), O = /* @__PURE__ */ new WeakMap(), N = /* @__PURE__ */ new WeakMap(), M = /* @__PURE__ */ new WeakMap(), R = /* @__PURE__ */ new WeakMap(), g = /* @__PURE__ */ new WeakSet(), /**
* Connect to the given URL and start receiving events
*
* @internal
*/
j = function() {
  u(this, E, this.CONNECTING), u(this, S, new AbortController()), a(this, D)(a(this, k), w(this, g, te).call(this)).then(a(this, q)).catch(a(this, J));
}, q = /* @__PURE__ */ new WeakMap(), J = /* @__PURE__ */ new WeakMap(), /**
* Get request options for the `fetch()` request
*
* @returns The request options
* @internal
*/
te = function() {
  var e;
  const t = {
    // [spec] Let `corsAttributeState` be `Anonymous`…
    // [spec] …will have their mode set to "cors"…
    mode: "cors",
    redirect: "follow",
    headers: { Accept: "text/event-stream", ...a(this, A) ? { "Last-Event-ID": a(this, A) } : void 0 },
    cache: "no-store",
    signal: (e = a(this, S)) == null ? void 0 : e.signal
  };
  return "window" in globalThis && (t.credentials = this.withCredentials ? "include" : "same-origin"), t;
}, X = /* @__PURE__ */ new WeakMap(), Y = /* @__PURE__ */ new WeakMap(), /**
* Handles the process referred to in the EventSource specification as "failing a connection".
*
* @param error - The error causing the connection to fail
* @param code - The HTTP status code, if available
* @internal
*/
W = function(e, t) {
  var n;
  a(this, E) !== this.CLOSED && u(this, E, this.CLOSED);
  const s = new V("error", { code: t, message: e });
  (n = a(this, N)) == null || n.call(this, s), this.dispatchEvent(s);
}, /**
* Schedules a reconnection attempt against the EventSource endpoint.
*
* @param message - The error causing the connection to fail
* @param code - The HTTP status code, if available
* @internal
*/
Z = function(e, t) {
  var n;
  if (a(this, E) === this.CLOSED)
    return;
  u(this, E, this.CONNECTING);
  const s = new V("error", { code: t, message: e });
  (n = a(this, N)) == null || n.call(this, s), this.dispatchEvent(s), u(this, B, setTimeout(a(this, z), a(this, U)));
}, z = /* @__PURE__ */ new WeakMap(), /**
* ReadyState representing an EventSource currently trying to connect
*
* @public
*/
$.CONNECTING = 0, /**
* ReadyState representing an EventSource connection that is open (eg connected)
*
* @public
*/
$.OPEN = 1, /**
* ReadyState representing an EventSource connection that is closed (eg disconnected)
*
* @public
*/
$.CLOSED = 2;
Object.defineProperty($, Symbol.for("eventsource.supports-fetch-override"), {
  value: !0,
  writable: !1,
  configurable: !1,
  enumerable: !1
});
function ge() {
  const e = "document" in globalThis ? globalThis.document : void 0;
  return e && typeof e == "object" && "baseURI" in e && typeof e.baseURI == "string" ? e.baseURI : void 0;
}
const ye = 3e3, we = 6e4, Se = 15, ne = _e();
function _e() {
  var t, n;
  const e = (n = (t = globalThis.crypto) == null ? void 0 : t.randomUUID) == null ? void 0 : n.call(t);
  return e || `sse-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}
function Ne() {
  const e = fe(), t = he();
  function n(i) {
    return Math.min(ye * 2 ** i, we);
  }
  function s(i, r) {
    let o = null, l = null, f = 0, v = !1;
    function C() {
      var c;
      const y = ((c = t.sessionUser.value) == null ? void 0 : c.token) ?? "";
      if (v || !y) return;
      l && (clearTimeout(l), l = null);
      const T = e.getSubscribeUrl(ne, i.type, i.params), m = new $(T, {
        fetch: (h, d) => fetch(h, {
          ...d,
          headers: {
            ...(d == null ? void 0 : d.headers) ?? {},
            authorization: `Bearer ${y}`
          }
        })
      });
      o = m, m.onopen = () => {
        f = 0;
      }, m.onmessage = (h) => {
        try {
          if (!h.data) return;
          const d = JSON.parse(h.data), L = d.data ? typeof d.data == "string" ? JSON.parse(d.data) : d.data : d;
          Promise.resolve(r(L)).catch((x) => {
            console.error("Failed to handle SSE message", x);
          });
        } catch (d) {
          console.error("Failed to parse SSE message", d);
        }
      }, m.onerror = () => {
        if (o === m && (o = null), m.close(), !v) {
          if (f >= Se) {
            console.warn("SSE subscription reconnect retries exhausted", i.type);
            return;
          }
          const h = n(f);
          f += 1, l = setTimeout(() => C(), h);
        }
      };
    }
    C();
    const _ = e.getStatus(i.type, i.params).catch((y) => (console.error("Failed to fetch initial state", y), null));
    return {
      unsubscribe: () => {
        v = !0, l && (clearTimeout(l), l = null), o && (o.close(), o = null);
      },
      initialState: _
    };
  }
  return {
    clientId: ne,
    subscribe: s
  };
}
export {
  Ne as a,
  Be as u
};
