// services/fetchAnalogeEingaengeService.ts

export const fetchAnalogeEingaengeService = async (): Promise<Record<
  string,
  any
> | null> => {
  try {
    if (typeof window === "undefined") return null;

    const isDevelopment = process.env.NEXT_PUBLIC_NODE_ENV === "development";

    const scriptSrc = isDevelopment
      ? "/api/cpl/analogeEingaengeAPIHandler"
      : "/CPL?/CPL/SERVICE/ae.js";

    await new Promise<void>((resolve, reject) => {
      const script = document.createElement("script");
      script.src = scriptSrc;
      script.async = true;
      script.onload = () => resolve();
      script.onerror = () => reject(`❌ Error loading ${scriptSrc}`);
      document.body.appendChild(script);
    });

    // Now read the real variables
    const values = (window as any).win_analogInputsValues || [];
    const names = (window as any).win_analogInputsNames || [];
    const units = (window as any).win_analogInputsUnits || [];
    const factor = (window as any).win_analogInputsFactor || [];
    const offset = (window as any).win_analogInputsOffset || [];
    const weighting = (window as any).win_analogInputsWeighting || [];
    const loggerInterval =
      (window as any).win_analogInputsloggerIntervall || [];

    const result: Record<string, any> = {};

    for (let i = 0; i < values.length; i++) {
      result[`analogInput${i + 1}`] = {
        id: i + 1,
        value: values[i],
        name: names[i],
        unit: units[i],
        factor: factor[i],
        offset: offset[i],
        weighting: weighting[i],
        loggerInterval: loggerInterval[i],
      };
    }

    return result;
  } catch (error) {
    console.error("❌ Error loading analog inputs:", error);
    return null;
  }
};
