// pages/api/cpl/updateTdrSettingsDataAPIHandler.ts

import path from "path";
import fs from "fs/promises";

export default async function handler(req, res) {
  const updates = req.body?.updates;

  if (!Array.isArray(updates) || updates.length === 0) {
    return res.status(400).json({ error: "Missing or invalid updates array" });
  }

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

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

    for (const { key, slot, value } of updates) {
      const regex = new RegExp(`var\\s+${key}\\s*=\\s*\\[[^\\]]*\\]\\s*;`, "m");
      const match = fileContent.match(regex);

      if (!match) {
        console.warn(`Key "${key}" not found in file.`);
        continue;
      }

      const arrayRaw = match[0].match(/\[(.*)\]/s)?.[1] || "";
      let values = arrayRaw
        .split(",")
        .map((v) => v.trim())
        .map((v) => (v === "" ? "0" : v))
        .slice(0, 32);

      values[Number(slot)] = Number(value);

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

    // Bereinige kaputte Endzeilen wie ")"
    fileContent = fileContent.replace(
      /^\s*[\)\(a-zA-Z0-9\/\:\. ]{2,40}\s*$/gm,
      ""
    );

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

    return res.status(200).json({ success: true, updated: updates.length });
  } catch (err) {
    console.error("API error:", err);
    return res.status(500).json({ error: "Internal server error." });
  }
}
