// fetchSystemVoltTempService.ts

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

  const isProduction = process.env.NEXT_PUBLIC_NODE_ENV === "production";

  const scriptSrc = isProduction
    ? "/CPL?/CPL/SERVICE/systemVoltTemp.js"
    : "/api/cpl/systemVoltTempAPIHandler";

  await new Promise<void>((resolve, reject) => {
    const script = document.createElement("script");
    script.src = scriptSrc;
    script.async = true;
    script.onload = () => resolve();
    script.onerror = () =>
      reject("❌ Fehler beim Laden von systemVoltTempMockData.js");
    document.body.appendChild(script);
  });

  const win = window as any;
  let rawData: any;

  if (isProduction) {
    rawData = win.win_systemVoltTemp; // Produktion
  } else {
    rawData = win.win_systemVoltTempMockData; // Entwicklung
  }

  if (!rawData) {
    console.warn("⚠️ SystemVoltTemp-Daten fehlen oder ungültig:", rawData);
    return null;
  }

  const result = {
    "+15V": rawData[0],
    "+5V": rawData[1],
    "-15V": rawData[2],
    "-98V": rawData[3],
    "ADC Temp": rawData[4], // Achtung: Hier 'ADC Temp' anstatt "Temperatur AD Wandler"
    "CPU Temp": rawData[5], // 'CPU Temp' anstatt "Temperatur CPU"
  };

  return result;
};
