/**
 * Lazy Laravel Echo + pusher-js bootstrap (Team Workspaces P6 / Tier 2 —
 * Reverb opt-in).
 *
 * This module has NO top-level side effects: it does NOT construct an Echo
 * instance, open a websocket, or touch `window` on import. It only builds an
 * Echo client when `createEcho(config)` is called with a non-null Reverb
 * config — which only happens when an operator has flipped `collab.transport`
 * to 'reverb' (admin Realtime Settings card) AND a running `reverb:start`
 * process is reachable. On the default 'lock' transport `createEcho` is never
 * called, so nothing here executes (honors CLAUDE.md §Don'ts — Reverb is never
 * the shared/default path).
 *
 * Echo is configured for the Reverb (Pusher-protocol) backend. Auth rides the
 * existing session cookie via `/broadcasting/auth` with the XSRF header, so no
 * extra token plumbing is needed.
 */

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

export type ReverbClientConfig = {
    key: string;
    host: string;
    port: number;
    scheme: 'http' | 'https';
};

export type EchoInstance = Echo<'reverb'>;

function readXsrfCookie(): string | undefined {
    const match = document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/);
    return match ? decodeURIComponent(match[1]!) : undefined;
}

/**
 * Build a Reverb-backed Echo client from the server `collab.reverb` prop.
 * Returns null when the config is absent (transport=lock or misconfigured) so
 * callers can fall back to the LockAdapter and never run unprotected.
 */
export function createEcho(config: ReverbClientConfig | null): EchoInstance | null {
    if (!config || !config.key || !config.host) return null;

    const xsrf = readXsrfCookie();

    // pusher-js is the transport Echo's 'reverb' broadcaster drives. We keep it
    // local to this lazy module so it never loads on the default path.
    const client = new Echo<'reverb'>({
        broadcaster: 'reverb',
        Pusher,
        key: config.key,
        wsHost: config.host,
        wsPort: config.port,
        wssPort: config.port,
        forceTLS: config.scheme === 'https',
        enabledTransports: ['ws', 'wss'],
        // Auth via the session cookie — the editor is already authenticated.
        auth: {
            headers: {
                Accept: 'application/json',
                ...(xsrf ? { 'X-XSRF-TOKEN': xsrf } : {}),
            },
        },
    });

    return client;
}
