// services/fetchAnalogInputsHistoryService.ts

export async function fetchAnalogInputsHistoryService(): Promise<
  Record<number, any[]>
> {
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(today.getDate() - 1);

  const formatDate = (date: Date) =>
    `${date.getFullYear()};${String(date.getMonth() + 1).padStart(
      2,
      "0"
    )};${String(date.getDate()).padStart(2, "0")}`;

  const fromDate = formatDate(yesterday);
  const toDate = formatDate(today);

  const result: Record<number, any[]> = {};

  const isDev = process.env.NODE_ENV === "development";

  if (isDev) {
    // ⬇️ ENTWICKLUNG: über API-Handler
    const response = await fetch("/api/cpl/fetchAnalogInputsHistory");
    if (!response.ok) throw new Error("Fehler beim Laden der Mock-Daten");
    return await response.json();
  }

  // ⬇️ PRODUKTION: direkt vom CPL-Webserver holen
  for (let i = 0; i < 8; i++) {
    const inputNumber = i + 1;
    const sourceId = 99 + inputNumber;

    try {
      const url = `${window.location.origin}/CPL?Service/empty.acp&DIA0=${fromDate};${toDate};${sourceId};1`;
      const response = await fetch(url);
      if (!response.ok)
        throw new Error(`Fehler bei AE${inputNumber}: ${response.status}`);
      const data = await response.json();
      result[sourceId] = data;
    } catch (error) {
      console.error(`❌ Fehler beim Laden von AE${inputNumber}:`, error);
      result[sourceId] = [];
    }
  }

  return result;
}
