import fetch from "node-fetch";
import { Signal } from "../model/signal.js";
import { debug, error } from "../utils/logger.js";

const signalNames = ["s1", "s2", "s3", "s4", "s5", "s6"];

function startDataFetcher() {
  console.log("Scheduler wystartował");

  const seconds = 200;
  const intervalMs = 400;

  setInterval(async () => {
    const cutoff = Date.now() - seconds * 1000;

    for (let signalName of signalNames) {
      try {
        const res = await fetch(`https://bdijs.ontime24.ovh/api/z12/signal/${signalName}`);
        const data = await res.json();

        debug("Pobrane dane:", data);

        await Signal.updateOne(
          { sensor: data.sensor, timestamp: data.timestamp },
          {
            $set: {
              sensor: data.sensor,
              timestamp: data.timestamp,
              value: data.value,
              error: data.error
            }
          },
          { upsert: true }
        );
      } catch (err) {
        error("Błąd pobierania danych:", err.message);
      }
    }

    try {
      await Signal.deleteMany({ timestamp: { $lt: cutoff } });
    } catch (err) {
      error("Błąd usuwania starych danych:", err.message);
    }
  }, intervalMs);
}

export default startDataFetcher;