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

// Hilfsfunktion für künstliche Verzögerung
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    const logFilePath = path.join(
      process.cwd(),
      "mocks/device-cgi-simulator/settings/kueFirmwareUpdateLog.json"
    );

    const timestamp = new Date().toISOString();
    const logEntry = {
      timestamp,
      command: "&KSU99=1",
      message: "Firmwareupdate an alle KÜ-Module ausgelöst (Mock)",
    };

    let existingLog = [];
    if (fs.existsSync(logFilePath)) {
      const fileContent = fs.readFileSync(logFilePath, "utf-8");
      existingLog = JSON.parse(fileContent);
    }

    const updatedLog = [logEntry, ...existingLog].slice(0, 50);
    fs.writeFileSync(logFilePath, JSON.stringify(updatedLog, null, 2), "utf-8");

    console.log("🕒 Starte Firmware-Mock-Wartezeit (5 Minuten)...");
    await delay(10000); // 5 Minuten simulieren (300.000 ms)

    console.log("✅ Firmwareupdate-Mock abgeschlossen.");
    res.status(200).json({
      status: "success",
      log: logEntry,
    });
  } catch (error) {
    console.error("❌ Fehler beim Firmwareupdate-Mock:", error);
    res.status(500).json({
      status: "error",
      message: "Fehler beim Speichern des Firmwareupdates",
    });
  }
}
