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

// Hilfsfunktion: JSON-Datei laden
async function loadJsonData(filePath: string) {
  const data = await fs.readFile(filePath, "utf8");
  return JSON.parse(data);
}

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

  if (!slot || !messart || !dia) {
    return res.status(400).json({ error: "Missing required parameters" });
  }

  const jsonFilePath = path.join(
    process.cwd(),
    "apiMockData",
    "kuesChartData",
    `slot${slot}`,
    `${messart}`,
    `${dia}.json`
  );

  try {
    const jsonData = await loadJsonData(jsonFilePath);

    // Filtern nach Datum, wenn angegeben
    let filteredData = jsonData;
    if (vonDatum && bisDatum) {
      const von = new Date(`${vonDatum}T00:00:00`);
      const bis = new Date(`${bisDatum}T23:59:59`);

      filteredData = jsonData.filter((item: any) => {
        const timestamp = new Date(item.t);
        return timestamp >= von && timestamp <= bis;
      });
    }

    return res.status(200).json(filteredData);
  } catch (error) {
    return res.status(404).json({ error: "File not found or read error" });
  }
}
