import { QbitClient } from "../qbit/qbit.client"
import { tickLoopJobs } from "./loop.engine"
import { getStatusSnapshot, refreshJobsStatus, setTorrentsStatus } from "../status/status.service"
import { emitStatusUpdate } from "../realtime/emitter"
import { logger } from "../utils/logger"

export const startLoopScheduler = (qbit: QbitClient, intervalMs: number) => {
  setInterval(async () => {
    try {
      const torrents = await qbit.getTorrentsInfo();
      const transfer = await qbit.getTransferInfo();
      setTorrentsStatus(torrents, transfer);
      await tickLoopJobs(qbit, torrents);
      const jobs = await refreshJobsStatus();
      const current = await getStatusSnapshot();
      emitStatusUpdate({
        qbit: { ...current.qbit, ok: true },
        torrents,
        transfer,
        jobs,
      });
    } catch (error) {
      logger.error({ error }, "Loop scheduler tick failed");
    }
  }, intervalMs);
};
