import { ensureQueryFn as K, addToStart as Q, addToEnd as b, addConsumeAwareSignal as k } from "./utils.js";
function N(s) {
  return {
    onFetch: (e, r) => {
      const t = e.options, u = e.fetchOptions?.meta?.fetchMore?.direction, g = e.state.data?.pages || [], c = e.state.data?.pageParams || [];
      let i = { pages: [], pageParams: [] }, l = 0;
      const P = async () => {
        let d = !1;
        const w = (a) => {
          k(
            a,
            () => e.signal,
            () => d = !0
          );
        }, q = K(e.options, e.fetchOptions), m = async (a, n, o) => {
          if (d)
            return Promise.reject();
          if (n == null && a.pages.length)
            return Promise.resolve(a);
          const v = (() => {
            const h = {
              client: e.client,
              queryKey: e.queryKey,
              pageParam: n,
              direction: o ? "backward" : "forward",
              meta: e.options.meta
            };
            return w(h), h;
          })(), C = await q(v), { maxPages: f } = e.options, y = o ? Q : b;
          return {
            pages: y(a.pages, C, f),
            pageParams: y(a.pageParams, n, f)
          };
        };
        if (u && g.length) {
          const a = u === "backward", n = a ? S : F, o = {
            pages: g,
            pageParams: c
          }, p = n(t, o);
          i = await m(o, p, a);
        } else {
          const a = s ?? g.length;
          do {
            const n = l === 0 ? c[0] ?? t.initialPageParam : F(t, i);
            if (l > 0 && n == null)
              break;
            i = await m(i, n), l++;
          } while (l < a);
        }
        return i;
      };
      e.options.persister ? e.fetchFn = () => e.options.persister?.(
        P,
        {
          client: e.client,
          queryKey: e.queryKey,
          meta: e.options.meta,
          signal: e.signal
        },
        r
      ) : e.fetchFn = P;
    }
  };
}
function F(s, { pages: e, pageParams: r }) {
  const t = e.length - 1;
  return e.length > 0 ? s.getNextPageParam(
    e[t],
    e,
    r[t],
    r
  ) : void 0;
}
function S(s, { pages: e, pageParams: r }) {
  return e.length > 0 ? s.getPreviousPageParam?.(e[0], e, r[0], r) : void 0;
}
export {
  N as infiniteQueryBehavior
};
