// /pages/api/cpl/updateDigitalOutputs.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 !== "POST") {
    return res.status(405).json({ error: "Method not allowed" });
  }

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

  try {
    const { outputs } = req.body;

    if (!Array.isArray(outputs) || outputs.length !== 4) {
      return res
        .status(400)
        .json({ error: "Ungültiges Datenformat (4 Einträge erwartet)" });
    }

    const stateArray = outputs.map((o) => (o.status ? 1 : 0)).join(", ");
    const labelArray = outputs.map((o) => `"${o.label}"`).join(", ");

    const fileContent = `win_da_state = [${stateArray}];\nwin_da_bezeichnung = [${labelArray}];\n`;

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

    return res
      .status(200)
      .json({ message: "Mockdaten erfolgreich gespeichert." });
  } catch (error) {
    return res
      .status(500)
      .json({ error: "Speichern fehlgeschlagen", detail: error });
  }
}
