import { Signal } from "../model/signal.js";

const signalData = async function(req, res, next) {
  const signalName = req.params.sensor;
  const allowedSignals = ["s1", "s2", "s3", "s4", "s5", "s6"];

  if (!allowedSignals.includes(signalName)) {
    req.d = { name: signalName, x: [], y: [] };
    next();
    return;
  }

  try {
    const cutoff = Date.now() - 200 * 1000;

    const signals = await Signal.find({
      sensor: signalName,
      timestamp: { $gte: cutoff }
    })
      .sort({ timestamp: 1 });

    const x = signals.map(s => s.timestamp);
    const y = signals.map(s => s.value);

    req.d = {
      name: signalName,
      x: x,
      y: y
    };
  } catch (err) {
    console.error("Błąd pobierania sygnałów:", err);
    req.d = { name: signalName, x: [], y: [] };
  }

  next();
};

export default signalData;