import Echo from "laravel-echo";
import * as PusherModule from "pusher-js";

/**
 * `pusher-js` ships a UMD-ish browser build with no ESM `default` export; resolve the
 * constructor everywhere Vite/esbuild/Node interop differ.
 *
 * @returns {import("pusher-js").default | null}
 */
function pusherConstructor() {
  const d = PusherModule.default;
  if (typeof d === "function") {
    return /** @type {import("pusher-js").default} */ (d);
  }
  if (d != null && typeof d.Pusher === "function") {
    return /** @type {import("pusher-js").default} */ (d.Pusher);
  }
  if (typeof PusherModule.Pusher === "function") {
    return /** @type {import("pusher-js").default} */ (PusherModule.Pusher);
  }

  return null;
}

/** @type {Echo | null | undefined} undefined = not evaluated yet */
let echoCache;

/**
 * Laravel Reverb via Echo (lazy). Returns null when VITE_REVERB_APP_KEY is absent.
 */
export default function realtimeEcho() {
  if (echoCache !== undefined) {
    return echoCache;
  }
  const key = import.meta.env.VITE_REVERB_APP_KEY;
  if (!key) {
    echoCache = null;

    return null;
  }

  const Pusher = pusherConstructor();
  if (!Pusher) {
    echoCache = null;
    console.warn(
      "[realtime] Could not load Pusher client from pusher-js; Reverb disabled.",
    );

    return null;
  }

  window.Pusher = Pusher;
  echoCache = new Echo({
    broadcaster: "reverb",
    key,
    wsHost: import.meta.env.VITE_REVERB_HOST,
    wsPort: Number(import.meta.env.VITE_REVERB_PORT || 80),
    wssPort: Number(import.meta.env.VITE_REVERB_PORT || 443),
    forceTLS:
      String(import.meta.env.VITE_REVERB_SCHEME ?? "").toLowerCase() === "https",
    enabledTransports: ["ws", "wss"],
    withCredentials: true,
  });

  return echoCache;
}
