import type { ManagerOptions, SocketOptions } from "socket.io-client";
import { getGatewayUrl } from "./public-env";

/**
 * Shared Socket.IO client options for the gateway.
 *
 * Prefer WebSocket first. Polling-only behind Apache often produced Engine.IO
 * "Session ID unknown" (code 1) when long-poll requests lost stickiness, which
 * silently broke call signalling mid-negotiation.
 *
 * `upgrade: false` avoids the polling→websocket upgrade path that previously
 * caused TRANSPORT_MISMATCH (code 3) when Upgrade headers were stripped.
 * If websocket cannot connect, the client falls back to polling alone.
 */
export function gatewaySocketOptions(
  auth: (cb: (data: { accessToken: string | null }) => void) => void,
): Partial<ManagerOptions & SocketOptions> {
  return {
    path: "/socket.io/",
    transports: ["websocket", "polling"],
    upgrade: false,
    rememberUpgrade: false,
    reconnection: true,
    reconnectionAttempts: Infinity,
    reconnectionDelay: 500,
    reconnectionDelayMax: 5_000,
    timeout: 20_000,
    auth,
  };
}

export function gatewayUrl(): string {
  return getGatewayUrl();
}
