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

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

  const updates = req.body.updates;

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

  const filePath = path.join(
    process.cwd(),
    "mocks/device-cgi-simulator/SERVICE/analogInputsMockData.json"
  );
  const content = fs.readFileSync(filePath, "utf-8");
  const data = JSON.parse(content);

  for (const update of updates) {
    const { key, index, value } = update;
    if (Array.isArray(data[key]) && index < data[key].length) {
      data[key][index] = value;
    }
  }

  fs.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf-8");
  return res.status(200).json({ success: true });
}
