// /services/fetchLast20MessagesService.ts

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

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

  const scriptSrc = isDev
    ? "/api/cpl/last20MessagesAPIHandler" // in Dev → per API geladen
    : "/CPL?/CPL/SERVICE/Start.js"; // in Prod → echtes Script vom CPL

  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;
};
