// ✅ Service: /services/fetchDigitaleEingaengeService.ts

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

    // ✅ de.js nur bei Bedarf nachladen (Pfad abhängig von Umgebung)
    const scriptSrc =
      process.env.NEXT_PUBLIC_NODE_ENV === "production"
        ? "/CPL?/CPL/SERVICE/de.js"
        : "/api/cpl/digitaleEingaengeAPIHandler";

    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 de.js");
      document.body.appendChild(script);
    });

    const win = window as any;

    if (!Array.isArray(win.win_de_state)) {
      console.warn("⚠️ win_de_state ist nicht vorhanden oder kein Array");
      return [];
    }

    const formattedData = win.win_de_state.map((status, index) => ({
      id: index + 1,
      label: win.win_de_label?.[index] || `DE${index + 1}`,
      name: win.win_de_label?.[index] || "",

      status: status === 1,
      counter: win.win_de_counter?.[index] || 0,
      flutter: win.win_flutter?.[index] || 0,
      invertierung: win.win_de_invert?.[index] === 1,

      // 🔽 NEU:
      filterzeit: win.win_de_time_filter?.[index] || 0,
      gewichtung: win.win_de_weighting?.[index] || 0,
      zaehlerAktiv: win.win_de_counter_active?.[index] === 1,
      eingangOffline: win.win_de_offline?.[index] === 1,
    }));

    return formattedData;
  } catch (error) {
    console.error("❌ Fehler beim Laden der digitalen Eingänge:", error);
    return null;
  }
};
