// pages/api/cpl/updateTdrSettingsDataAPIHandler.ts import path from "path"; import fs from "fs/promises"; import type { NextApiRequest, NextApiResponse } from "next"; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { 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(), "device-cgi-simulator/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] || ""; const values = arrayRaw .split(",") .map((v) => v.trim()) .map((v) => (v === "" ? "0" : v)) .slice(0, 32); values[Number(slot)] = String(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." }); } }