import { config } from "../config";
import { logger } from "../utils/logger";
import { runDueWatchers, runWatcherById } from "./watcher.service";

const activeRuns = new Set<string>();

export const startWatcherWorker = (intervalMs: number) => {
  if (!config.watcherEnabled) {
    logger.info("Watcher worker disabled");
    return;
  }
  setInterval(async () => {
    try {
      const dueWatcherIds = await runDueWatchers();
      logger.info({ count: dueWatcherIds.length, watcherIds: dueWatcherIds }, "Watcher worker tick");
      for (const watcherId of dueWatcherIds) {
        if (activeRuns.has(watcherId)) {
          logger.info({ watcherId }, "Watcher run skipped because another run is active");
          continue;
        }
        activeRuns.add(watcherId);
        runWatcherById(watcherId)
          .catch((error) => {
            logger.error({ error, watcherId }, "Unhandled watcher run failure");
          })
          .finally(() => {
            activeRuns.delete(watcherId);
          });
      }
    } catch (error) {
      logger.error({ error }, "Watcher worker tick failed");
    }
  }, intervalMs);
};
