/**
 * Derives the WebSocket base URL.
 *
 * Priority:
 *  1. `VITE_WS_URL` env var — explicit override (e.g. wss://example.com)
 *  2. Current page origin — uses window.location so the request goes through
 *     whatever proxy is in front (Vite dev proxy or nginx in production).
 *     This avoids hardcoding the backend port and bypassing the proxy.
 */
export function getChatSocketUrl(chatId: number | string): string {
  const explicit = import.meta.env.VITE_BACKEND_WS_URL as string | undefined;
  if (explicit) {
    return `${stripTrailing(explicit)}/ws/chat/${chatId}/`;
  }

  // Derive scheme from page protocol, host from page host (preserves dev port)
  const wsScheme = window.location.protocol === "https:" ? "wss:" : "ws:";
  return `${wsScheme}//${window.location.host}/ws/chat/${chatId}/`;
}

function stripTrailing(s: string): string {
  return s.endsWith("/") ? s.slice(0, -1) : s;
}
