// ✅ Service: /services/fetchDigitalOutputs.ts

export const fetchDigitalOutputs = async () => {
  if (typeof window === "undefined") return [];

  // ✅ da.js nur bei Bedarf nachladen (Pfad abhängig von Umgebung)
  const scriptSrc =
    process.env.NODE_ENV === "production"
      ? "/CPL?/CPL/SERVICE/da.js"
      : "/CPLmockData/SERVICE/da.js";

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

  const win = window as any;

  const state = win.win_da_state;
  const labels = win.win_da_bezeichnung;

  if (
    Array.isArray(state) &&
    Array.isArray(labels) &&
    state.length === labels.length
  ) {
    return state.map((status: number, index: number) => ({
      id: index + 1,
      label: labels[index] || `Ausgang ${index + 1}`,
      status: status === 1,
    }));
  } else {
    console.warn("⚠️ Digitale Ausgänge unvollständig oder inkonsistent:", {
      state,
      labels,
    });
    return [];
  }
};
