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

interface UpdateRequest {
  updates: Array<{
    key: "kvzPresence" | "kvzActive" | "kvzStatus";
    slot?: number;
    ledIndex?: number;
    value: number;
  }>;
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<KvzData | { error: string }>
) {
  if (req.method !== "POST") {
    res.setHeader("Allow", ["POST"]);
    return res.status(405).json({ error: `Method ${req.method} not allowed` });
  }

  try {
    const { updates }: UpdateRequest = req.body;

    if (!Array.isArray(updates)) {
      return res.status(400).json({ error: "Updates muss ein Array sein" });
    }

    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);

    // Updates anwenden
    updates.forEach((update) => {
      const { key, slot, ledIndex, value } = update;

      if (key === "kvzPresence" && typeof slot === "number") {
        if (slot >= 0 && slot < 32) {
          kvzData.kvzPresence[slot] = value;
        }
      } else if (key === "kvzActive" && typeof slot === "number") {
        if (slot >= 0 && slot < 32) {
          kvzData.kvzActive[slot] = value;
        }
      } else if (
        key === "kvzStatus" &&
        typeof slot === "number" &&
        typeof ledIndex === "number"
      ) {
        const arrayIndex = slot * 4 + ledIndex;
        if (arrayIndex >= 0 && arrayIndex < 128) {
          kvzData.kvzStatus[arrayIndex] = value;
        }
      }
    });

    // Timestamp aktualisieren
    kvzData.timestamp = new Date().toISOString();

    // Datei speichern
    fs.writeFileSync(filePath, JSON.stringify(kvzData, null, 2));

    res.status(200).json(kvzData);
  } catch (error) {
    console.error("Fehler beim Update der KVZ-Einstellungen:", error);
    res.status(500).json({ error: "Fehler beim Update der KVZ-Einstellungen" });
  }
}
