// /services/fetchLast20Messages.ts

export const fetchLast20MessagesFromWindow = async (): Promise<
  string | null
> => {
  if (typeof window === "undefined") return null;

  // ✅ Start.js nur bei Bedarf nachladen (Pfad abhängig von Umgebung)
  const scriptSrc =
    process.env.NODE_ENV === "production"
      ? "/CPL?/CPL/SERVICE/Start.js"
      : "/CPLmockData/SERVICE/Start.js";

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

  const raw = (window as any).win_last20Messages;

  return raw ? String(raw) : null;
};
