// pages/api/kvz/data.ts
import type { NextApiRequest, NextApiResponse } from "next";
import fs from "fs";
import path from "path";

export interface KvzData {
  kvzPresence: number[];
  kvzActive: number[];
  kvzStatus: number[];
  timestamp: string;
  description?: {
    kvzPresence: string;
    kvzActive: string;
    kvzStatus: string;
  };
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<KvzData | { error: string }>
) {
  if (req.method === "GET") {
    try {
      const filePath = path.join(
        process.cwd(),
        "mocks",
        "device-cgi-simulator",
        "kvz",
        "kvzData.json"
      );
      const fileContents = fs.readFileSync(filePath, "utf8");
      const kvzData: KvzData = JSON.parse(fileContents);

      // Update timestamp to current time
      kvzData.timestamp = new Date().toISOString();

      res.status(200).json(kvzData);
    } catch (error) {
      console.error("Fehler beim Lesen der KVZ-Daten:", error);
      res.status(500).json({ error: "Fehler beim Laden der KVZ-Daten" });
    }
  } else if (req.method === "POST") {
    try {
      const { kvzPresence, kvzActive, kvzStatus } = req.body;

      if (
        !Array.isArray(kvzPresence) ||
        !Array.isArray(kvzActive) ||
        !Array.isArray(kvzStatus)
      ) {
        return res.status(400).json({ error: "Ungültige Datenstruktur" });
      }

      if (kvzPresence.length !== 32) {
        return res
          .status(400)
          .json({ error: "kvzPresence muss 32 Elemente haben" });
      }

      if (kvzActive.length !== 32) {
        return res
          .status(400)
          .json({ error: "kvzActive muss 32 Elemente haben" });
      }

      if (kvzStatus.length !== 128) {
        return res
          .status(400)
          .json({ error: "kvzStatus muss 128 Elemente haben" });
      }

      const filePath = path.join(
        process.cwd(),
        "mocks",
        "device-cgi-simulator",
        "kvz",
        "kvzData.json"
      );
      const fileContents = fs.readFileSync(filePath, "utf8");
      const existingData: KvzData = JSON.parse(fileContents);

      const updatedData: KvzData = {
        ...existingData,
        kvzPresence,
        kvzActive,
        kvzStatus,
        timestamp: new Date().toISOString(),
      };

      fs.writeFileSync(filePath, JSON.stringify(updatedData, null, 2));

      res.status(200).json(updatedData);
    } catch (error) {
      console.error("Fehler beim Speichern der KVZ-Daten:", error);
      res.status(500).json({ error: "Fehler beim Speichern der KVZ-Daten" });
    }
  } else {
    res.setHeader("Allow", ["GET", "POST"]);
    res.status(405).json({ error: `Method ${req.method} not allowed` });
  }
}
