/**
 * Interval scheduler for the bridge command poller. Mirrors startSyncTicker:
 * an overlap-guarded runNow(), a non-rejecting cycle (errors routed to onError),
 * setInterval with unref() so it never blocks process exit, and a clean stop().
 */
import { pollCommandsOnce, } from "./commandPoller.js";
export function startCommandPollTicker(input) {
    let stopped = false;
    let running = null;
    async function runNow() {
        if (stopped || running)
            return running ?? Promise.resolve();
        running = Promise.resolve()
            .then(() => pollCommandsOnce(input.store, input.config, {
            ...(input.requester ? { requester: input.requester } : {}),
            ...(input.deviceSigner ? { deviceSigner: input.deviceSigner } : {}),
        }))
            .then(() => (input.afterPoll ? input.afterPoll() : undefined))
            .then(() => undefined)
            .catch((error) => {
            // A failed poll cycle must not reject runNow() — the interval tick and
            // any manual caller both rely on it resolving — but the error is
            // surfaced to the 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);
        },
    };
}
