import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

/**
 * Shared Reverb/Echo connection.
 *
 * In production the browser talks to wss://<host>/app, which Apache proxies to
 * the Reverb server on 127.0.0.1:8081. VITE_REVERB_HOST/PORT only apply in dev.
 *
 * Returns null when no key is configured — every caller must cope with that and
 * fall back to polling, so the app still works if the socket is unavailable.
 */
let shared: Echo<'reverb'> | null | undefined;
let sharedKey = '';

export function getEcho(runtimeKey = ''): Echo<'reverb'> | null {
  const key = runtimeKey || import.meta.env.VITE_REVERB_APP_KEY || '';
  if (shared !== undefined && sharedKey === key) return shared;
  if (shared && sharedKey !== key) shared.disconnect();
  shared = undefined;
  sharedKey = key;

  if (!key) {
    shared = null;
    return shared;
  }

  try {
    const secure = window.location.protocol === 'https:';
    const useDevEndpoint = import.meta.env.DEV && !!import.meta.env.VITE_REVERB_HOST;
    (window as unknown as Record<string, unknown>).Pusher = Pusher;

    shared = new Echo({
      broadcaster: 'reverb',
      key,
      wsHost: useDevEndpoint ? import.meta.env.VITE_REVERB_HOST : window.location.hostname,
      wsPort: useDevEndpoint ? Number(import.meta.env.VITE_REVERB_PORT ?? 8081) : 80,
      wssPort: useDevEndpoint ? Number(import.meta.env.VITE_REVERB_PORT ?? 8081) : 443,
      forceTLS: useDevEndpoint ? (import.meta.env.VITE_REVERB_SCHEME ?? 'http') === 'https' : secure,
      enabledTransports: ['ws', 'wss'],
      disableStats: true,
    });
  } catch {
    shared = null;
  }

  return shared;
}
