// /services/fetchDigitalOutputsService.ts

export const fetchDigitalOutputsService = async () => {
  const mode = process.env.NEXT_PUBLIC_CPL_MODE;

  if (mode === "production") {
    const scriptUrl = "/CPL?/CPL/SERVICE/digitalOutputs.js";

    await new Promise<void>((resolve, reject) => {
      const script = document.createElement("script");
      script.src = scriptUrl;
      script.async = true;
      script.onload = () => resolve();
      script.onerror = () =>
        reject("❌ Fehler beim Laden der digitalOutputs.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 [];
    } else {
      return state.slice(0, 4).map((status: number, index: number) => ({
        id: index + 1,
        label:
          Array.isArray(labels) && labels[index]
            ? labels[index]
            : `Ausgang ${index + 1}`,
        status: status === 1,
      }));
    }
  } else if (mode === "json") {
    const res = await fetch("/api/cpl/getDigitalOutputsHandler");

    if (!res.ok) {
      throw new Error("❌ Fehler beim Laden der digitalen Ausgänge");
    } else {
      const data = await res.json();
      const state = data.win_da_state;
      const labels = data.win_da_bezeichnung;

      if (!Array.isArray(state)) {
        console.warn("⚠️ win_da_state fehlt oder ist ungültig:", state);
        return [];
      } else {
        return state.slice(0, 4).map((status: number, index: number) => ({
          id: index + 1,
          label:
            Array.isArray(labels) && labels[index]
              ? labels[index]
              : `Ausgang ${index + 1}`,
          status: status === 1,
        }));
      }
    }
  } else if (mode === "jsSimulatedProd") {
    console.log("🔄 Lade simulierte analoge Eingänge im Produktionsmodus...");
    const scriptUrl = "/api/cpl/getDigitalOutputsHandler"; // gibt JavaScript zurück
    await new Promise<void>((resolve, reject) => {
      const script = document.createElement("script");
      script.src = scriptUrl;
      script.async = true;
      script.onload = () => resolve();
      script.onerror = () =>
        reject("❌ Fehler beim Laden des simulierten Scripts");
      document.body.appendChild(script);
    });
    const win = window as any;
    return Array.from({ length: 4 }, (_, i) => ({
      id: i + 1,
      label: win.win_da_bezeichnung[i] || `Ausgang ${i + 1}`,
      status: win.win_da_state[i] === 1,
    }));
  } else {
    console.warn(`⚠️ Unbekannter Modus: ${mode}`);
    return [];
  }
};
