// /pages/api/cpl/updateKueSettingsDataAPIHandler.ts
import path from "path";
import fs from "fs/promises";

export default async function handler(req, res) {
  const { key, value, slot } = req.query;

  if (!key || slot === undefined) {
    return res.status(400).json({ error: "Missing key or slot parameter." });
  }

  const mockFilePath = path.join(
    process.cwd(),
    "apiMockData/SERVICE/kabelueberwachungMockData.js"
  );

  try {
    const fileContent = await fs.readFile(mockFilePath, "utf-8");

    const regex = new RegExp(`(var\\s+${key}\\s*=\\s*\\[)([^\\]]+)(\\])`);
    const match = fileContent.match(regex);

    if (!match) {
      return res
        .status(404)
        .json({ error: `Key "${key}" not found in mock data.` });
    }

    const values = match[2]
      .split(",")
      .map((v) => v.trim())
      .filter((_, i) => i < 32); // Optional: auf maximale Länge beschränken

    const needsQuoting = isNaN(Number(value)) && !/^["'].*["']$/.test(value);
    values[Number(slot)] = needsQuoting ? `"${value}"` : value;

    // Entferne leere Slots
    while (values.length > 0 && values[values.length - 1] === "") {
      values.pop();
    }

    // Ergänze fehlende Slots mit leerem String
    while (values.length < 32) {
      values.push('""'); // Leerstring mit Anführungszeichen
    }

    const newArray = `var ${key} = [\n  ${values.join(", ")}\n]`;

    const updated = fileContent.replace(regex, newArray);

    await fs.writeFile(mockFilePath, updated, "utf-8");

    return res.status(200).json({ success: true, key, slot, value });
  } catch (error) {
    console.error("Mock update failed:", error);
    return res.status(500).json({ error: "Internal server error." });
  }
}
