// ✅ 1. Service: /services/fetchOpcUaSettingsService.ts

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

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

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

    const win = window as any;

    const data = {
      zustand: win.win_opcUaZustand || "Offline",
      encryption: win.win_opcUaEncryption || "None",
      clientCount: win.win_opcUaActiveClientCount || 0,
      nodesetName: win.win_opcUaNodesetName || "DefaultNodeset",
      users: Array.isArray(win.win_opcUaUsers) ? win.win_opcUaUsers : [],
    };

    return data;
  } catch (error) {
    console.error("Fehler beim Laden der OPC UA Daten:", error);
    return null;
  }
};
