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

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== "GET") {
    return res.status(405).json({ error: "Only GET allowed" });
  }

  const slot = parseInt(req.query.slot as string);
  const key = req.query.key as string;
  const value = req.query.value as string;

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

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

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

    // Robuste Regex: matcht auch bei Zeilenumbrüchen oder Leerzeichen
    const regex = new RegExp(
      `(var\\s+${key}\\s*=\\s*\\[)([\\s\\S]*?)(\\])`,
      "gm"
    );

    const match = fileContent.match(regex);

    console.log("🔍 Suche nach Variable:", key);
    if (!match) {
      console.warn(`⚠️ Variable '${key}' nicht gefunden in Datei.`);
      return res.status(404).json({ error: `Variable '${key}' not found.` });
    }

    const arrayPart = match[0].match(/\[(.*)\]/s)?.[1] ?? "";
    const values = arrayPart
      .split(",")
      .map((v) => v.trim())
      .filter((v) => v.length > 0 || v === "");

    const parsedValue = isNaN(Number(value)) ? JSON.stringify(value) : value;

    if (slot >= values.length) {
      return res
        .status(400)
        .json({ error: `Slot ${slot} ist außerhalb des gültigen Bereichs.` });
    }

    values[slot] = parsedValue;
    const updatedArray = `var ${key} = [ ${values.join(", ")} ];`;

    fileContent = fileContent.replace(regex, updatedArray);

    await fs.writeFile(filePath, fileContent, "utf-8");

    console.log(`✅ ${key}[${slot}] erfolgreich geändert auf`, parsedValue);
    return res
      .status(200)
      .json({ success: true, key, slot, newValue: parsedValue });
  } catch (error) {
    console.error("❌ Fehler beim Schreiben der Datei:", error);
    return res.status(500).json({ error: "Failed to write mock file" });
  }
}
