// /pages/api/cpl/slotDataAPIHandler.ts
import { NextApiRequest, NextApiResponse } from "next";
import path from "path";
import fs from "fs";

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    const { slot, messart, dia, vonDatum, bisDatum } = req.query;

    if (!slot || !messart || !dia || !vonDatum || !bisDatum) {
      return res.status(400).json({ error: "❌ Fehlende Parameter" });
    }

    // Dateipfad zusammensetzen (bevorzugt chartsData; Fallback ohne chartsData für ältere Skriptversionen)
    const preferred = path.join(
      process.cwd(),
      "mocks",
      "device-cgi-simulator",
      "chartsData",
      "cable-monitoring-data",
      `slot${slot}`,
      `${messart}`,
      `${dia}.json`
    );
    const legacy = path.join(
      process.cwd(),
      "mocks",
      "device-cgi-simulator",
      "cable-monitoring-data",
      `slot${slot}`,
      `${messart}`,
      `${dia}.json`
    );
    const filePath = fs.existsSync(preferred)
      ? preferred
      : fs.existsSync(legacy)
      ? legacy
      : null;

    if (!filePath) {
      return res.status(404).json({
        error: `❌ Datei nicht gefunden. Erwartet unter \n- ${preferred}\n- ${legacy}`,
      });
    }

    const fileContent = fs.readFileSync(filePath, "utf-8");
    const jsonData = JSON.parse(fileContent);

    interface SlotDataEntry {
      t: string;
      [key: string]: unknown;
    }

    const fromDateStr = String(vonDatum);
    const toDateStr = String(bisDatum);

    const filtered = (jsonData as SlotDataEntry[]).filter(
      (entry: SlotDataEntry) => {
        if (!entry.t) return false;
        const dateStr = entry.t.split(" ")[0]; // Nur yyyy-mm-dd extrahieren
        return dateStr >= fromDateStr && dateStr <= toDateStr;
      }
    );

    res.status(200).json(filtered);
  } catch (error: unknown) {
    console.error("❌ Fehler beim Lesen der Slot-Daten:", error);
    res.status(500).json({ error: "❌ Interner Serverfehler" });
  }
}
