const DEFAULT_CLIENTS_APP_URL = "https://clients.xtablo.com";

const trimTrailingSlash = (value: string) => value.replace(/\/+$/, "");

export function getClientPortalUrl(path = "/") {
  const configuredUrl = import.meta.env.VITE_CLIENTS_APP_URL as string | undefined;
  const normalizedPath = path.startsWith("/") ? path : `/${path}`;

  const baseUrl = configuredUrl
    ? trimTrailingSlash(configuredUrl)
    : window.location.hostname === "app.xtablo.com"
      ? DEFAULT_CLIENTS_APP_URL
      : window.location.hostname.startsWith("app.")
        ? `${window.location.protocol}//clients.${window.location.hostname.slice(4)}${
            window.location.port ? `:${window.location.port}` : ""
          }`
        : DEFAULT_CLIENTS_APP_URL;

  return `${baseUrl}${normalizedPath}`;
}

export function redirectClientUserToPortal(path = "/") {
  window.location.replace(getClientPortalUrl(path));
}
