import { runSyncOnce } from "./syncWorker.js";
export function startSyncTicker(input) {
    let stopped = false;
    let running = null;
    async function runNow() {
        if (stopped || running)
            return running ?? Promise.resolve();
        running = Promise.resolve()
            .then(() => runSyncOnce(input.store, input.config, {
            workspaceIds: input.store.listWorkspaceIds(),
            ...(input.poster ? { poster: input.poster } : {}),
            ...(input.deviceSigner ? { deviceSigner: input.deviceSigner } : {}),
        }))
            .then(() => undefined)
            .catch((error) => {
            // A failed sync cycle must not reject runNow() — overlapping callers
            // and the interval tick both rely on it resolving — but the error is
            // surfaced to the supplied sink instead of being silently dropped.
            input.onError?.(error);
        })
            .finally(() => {
            running = null;
        });
        return running;
    }
    const timer = input.config.enabled
        ? setInterval(() => {
            void runNow();
        }, input.config.intervalMs)
        : null;
    timer?.unref?.();
    return {
        runNow,
        stop() {
            stopped = true;
            if (timer)
                clearInterval(timer);
        },
    };
}
