//  /services/fetchDigitalOutputsService.ts

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

  const scriptSrc =
    process.env.NEXT_PUBLIC_NODE_ENV === "production"
      ? "/CPL?/CPL/SERVICE/da.js"
      : "/api/cpl/digitalOutputsAPIHandler";

  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)) {
    console.warn("⚠️ win_da_state fehlt oder ist ungültig:", state);
    return [];
  }

  const outputs = state
    .slice(0, 4) // ✅ Nur die 4 Ausgänge verwenden
    .map((status: number, index: number) => ({
      id: index + 1,
      label:
        Array.isArray(labels) && labels[index]
          ? labels[index]
          : `Ausgang ${index + 1}`,
      status: status === 1,
    }));

  return outputs;
};
