/**
 * Derives the WebSocket base URL from env. Mirrors the BE Channels routing,
 * which lives behind the same host as the REST API.
 *
 * Set `VITE_WS_URL` to override (e.g. wss://example.com); otherwise we flip the
 * scheme of `VITE_BACKEND_URL`.
 */
export function getChatSocketUrl(chatId: number | string): string {
  const explicit = import.meta.env.VITE_WS_URL as string | undefined;
  if (explicit) {
    return `${stripTrailing(explicit)}/ws/chat/${chatId}/`;
  }
  const backend = (import.meta.env.VITE_BACKEND_URL as string | undefined)
    ?? "http://localhost:8000";
  const wsBase = backend.replace(/^http/, "ws");
  // WS endpoints live at the host root (/ws/chat/<id>/), not under /api/.
  const hostOnly = wsBase.replace(/\/api\/?$/, "");
  return `${stripTrailing(hostOnly)}/ws/chat/${chatId}/`;
}

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