export const fetchGisStationsMeasurementsService = async () => {
  const useMocks = process.env.NEXT_PUBLIC_USE_MOCKS === "true";
  const basePath = process.env.NEXT_PUBLIC_BASE_PATH || "";

  if (useMocks) {
    const mockBasePath = "/api/mocks/webservice/gisStationsMeasurements";
    const mockURL = `${window.location.origin}${mockBasePath}`;
    if (process.env.NEXT_PUBLIC_DEBUG_LOG === "true") {
      console.log("🧪 Mock-Modus aktiviert: fetchGisStationsMeasurementsService ", mockURL);
    }

    const response = await fetch("/api/mocks/webservice/gisStationsMeasurements");
    if (!response.ok) {
      throw new Error("Mockdaten konnten nicht geladen werden");
    }

    const mockData = await response.json();
    if (!Array.isArray(mockData.Statis)) {
      throw new Error("Ungültige Struktur: 'Statis' fehlt im Mock");
    }

    return mockData.Statis;
  } else {
    const baseUrl = `${window.location.protocol}//${window.location.hostname}:80${basePath}/ClientData/WebServiceMap.asmx`;

    const params = new URLSearchParams(window.location.search);
    const idMap = params.get("m");
    const idUser = params.get("u");

    const url = `${baseUrl}/GisStationsMeasurements?idMap=${idMap}&idUser=${idUser}`;
    if (process.env.NEXT_PUBLIC_DEBUG_LOG === "true") {
      console.log("📡 fetchGisStationsMeasurementsService URL:", url);
    }

    const response = await fetch(url);
    if (!response.ok) {
      const message = `❌ Fehler: ${response.status} ${response.statusText}`;
      console.error(message);
      throw new Error(message);
    }

    const text = await response.text();

    let jsonResponse;
    try {
      jsonResponse = JSON.parse(text);
    } catch (e) {
      console.error("❌ Fehler beim JSON-Parsing der Antwort:", text);
      throw new Error("Antwort ist kein gültiges JSON");
    }

    if (!Array.isArray(jsonResponse.Statis)) {
      throw new Error("Antwortstruktur ungültig – 'Statis' fehlt");
    }

    return jsonResponse.Statis;
  }
};
