import { notifyManager as n } from "./notifyManager.js";
import { Mutation as c } from "./mutation.js";
import { matchMutation as r, noop as f } from "./utils.js";
import { Subscribable as u } from "./subscribable.js";
var g = class extends u {
  constructor(t = {}) {
    super(), this.config = t, this.#e = /* @__PURE__ */ new Set(), this.#t = /* @__PURE__ */ new Map(), this.#s = 0;
  }
  #e;
  #t;
  #s;
  build(t, e, s) {
    const i = new c({
      client: t,
      mutationCache: this,
      mutationId: ++this.#s,
      options: t.defaultMutationOptions(e),
      state: s
    });
    return this.add(i), i;
  }
  add(t) {
    this.#e.add(t);
    const e = o(t);
    if (typeof e == "string") {
      const s = this.#t.get(e);
      s ? s.push(t) : this.#t.set(e, [t]);
    }
    this.notify({ type: "added", mutation: t });
  }
  remove(t) {
    if (this.#e.delete(t)) {
      const e = o(t);
      if (typeof e == "string") {
        const s = this.#t.get(e);
        if (s)
          if (s.length > 1) {
            const i = s.indexOf(t);
            i !== -1 && s.splice(i, 1);
          } else s[0] === t && this.#t.delete(e);
      }
    }
    this.notify({ type: "removed", mutation: t });
  }
  canRun(t) {
    const e = o(t);
    if (typeof e == "string") {
      const i = this.#t.get(e)?.find(
        (a) => a.state.status === "pending"
      );
      return !i || i === t;
    } else
      return !0;
  }
  runNext(t) {
    const e = o(t);
    return typeof e == "string" ? this.#t.get(e)?.find((i) => i !== t && i.state.isPaused)?.continue() ?? Promise.resolve() : Promise.resolve();
  }
  clear() {
    n.batch(() => {
      this.#e.forEach((t) => {
        this.notify({ type: "removed", mutation: t });
      }), this.#e.clear(), this.#t.clear();
    });
  }
  getAll() {
    return Array.from(this.#e);
  }
  find(t) {
    const e = { exact: !0, ...t };
    return this.getAll().find(
      (s) => r(e, s)
    );
  }
  findAll(t = {}) {
    return this.getAll().filter((e) => r(t, e));
  }
  notify(t) {
    n.batch(() => {
      this.listeners.forEach((e) => {
        e(t);
      });
    });
  }
  resumePausedMutations() {
    const t = this.getAll().filter((e) => e.state.isPaused);
    return n.batch(
      () => Promise.all(
        t.map((e) => e.continue().catch(f))
      )
    );
  }
};
function o(t) {
  return t.options.scope?.id;
}
export {
  g as MutationCache
};
