const CHAT_SOCKET_PATH = "/ingress/agent/ws/chat";

type LocationLike = {
  protocol: string;
  host: string;
};

const toWsProtocol = (protocol: string) => {
  if (protocol === "https:" || protocol === "wss:") return "wss:";
  return "ws:";
};

const resolveChatPath = (pathname: string) => {
  const normalizedPath = pathname === "/" ? "" : pathname.replace(/\/$/, "");

  if (!normalizedPath) return CHAT_SOCKET_PATH;
  if (normalizedPath === CHAT_SOCKET_PATH) return CHAT_SOCKET_PATH;
  if (CHAT_SOCKET_PATH.startsWith(`${normalizedPath}/`)) return CHAT_SOCKET_PATH;

  return `${normalizedPath}${CHAT_SOCKET_PATH}`;
};

export const resolveChatSocketUrl = (
  rawSocketBaseUrl: unknown,
  currentLocation: LocationLike = window.location,
) => {
  const socketBaseUrl =
    typeof rawSocketBaseUrl === "string" ? rawSocketBaseUrl.trim() : "";
  const fallbackProtocol = toWsProtocol(currentLocation.protocol);

  if (!socketBaseUrl) {
    return `${fallbackProtocol}//${currentLocation.host}${CHAT_SOCKET_PATH}`;
  }

  if (/^(https?|wss?):\/\//.test(socketBaseUrl)) {
    const url = new URL(socketBaseUrl);
    url.protocol = toWsProtocol(url.protocol);
    url.pathname = resolveChatPath(url.pathname);
    return url.toString().replace(/\/$/, "");
  }

  const normalizedPath = socketBaseUrl.startsWith("/")
    ? socketBaseUrl
    : `/${socketBaseUrl}`;

  return `${fallbackProtocol}//${currentLocation.host}${resolveChatPath(normalizedPath)}`;
};
