// ✅ Service: /services/fetchKueDataService.ts

const devScriptPath = "/api/cpl/kabelueberwachungAPIHandler";
const prodScriptPath = "/CPL?/CPL/SERVICE/kueData.js";

export const fetchKueDataService = async () => {
  try {
    if (typeof window === "undefined") return null;

    const scriptPath =
      process.env.NEXT_PUBLIC_NODE_ENV === "production"
        ? prodScriptPath
        : devScriptPath;

    // ✅ Nur bei Bedarf nachladen
    await new Promise<void>((resolve, reject) => {
      const script = document.createElement("script");
      script.src = scriptPath;
      script.async = true;
      script.onload = () => resolve();
      script.onerror = () => reject("❌ Fehler beim Laden von kueData.js");
      document.body.appendChild(script);
    });

    const win = window as any;

    return {
      kueOnline: win.win_kueOnline || [],
      kueID: win.win_kueID || [],
      kuePSTmMinus96V: win.win_kuePSTmMinus96V || [],
      kueAlarm1: win.win_kueAlarm1 || [],
      kueAlarm2: win.win_kueAlarm2 || [],
      kueIso: win.win_kueIso || [],
      kueResidence: win.win_kueResidence || [],
      kueCableBreak: win.win_kueCableBreak || [],
      kueGroundFault: win.win_kueGroundFault || [],
      kueLimit1: win.win_kueLimit1 || [],
      kueLimit2Low: win.win_kueLimit2Low || [],
      kueDelay1: win.win_kueDelay1 || [],
      kueLoopInterval: win.win_kueLoopInterval || [],
      kueVersion: win.win_kueVersion || [],
      kueOverflow: win.win_kueOverflow || [],

      // TDR-Daten
      tdrAtten: win.win_tdrAtten || [],
      tdrPulse: win.win_tdrPulse || [],
      tdrSpeed: win.win_tdrSpeed || [],
      tdrAmp: win.win_tdrAmp || [],
      tdrTrigger: win.win_tdrTrigger || [],
      tdrLocation: win.win_tdrLocation || [],
      tdrActive: win.win_tdrActive || [],
      tdrLast: win.win_tdrLast || [],
      tdrOverflow: win.win_kueOverflow || [],
      //
      memoryInterval: win.win_memoryInterval || [],
    };
  } catch (error) {
    console.error("❌ Fehler beim Laden der KÜE-Daten:", error);
    return null;
  }
};
