const DEFAULT_MASTER_URL = "http://localhost:5174";

function readEnvLoginUrl() {
  if (typeof import.meta !== "undefined" && import.meta.env) {
    const vite = import.meta.env.VITE_HSE_LOGIN_URL;
    if (vite != null && String(vite).trim() !== "") {
      return String(vite).trim();
    }
    const portal = import.meta.env.VITE_MASTER_DASHBOARD_URL;
    if (portal != null && String(portal).trim() !== "") {
      return `${String(portal).trim().replace(/\/+$/, "")}/login`;
    }
  }
  if (typeof process !== "undefined" && process.env) {
    const cra =
      process.env.REACT_APP_HSE_LOGIN_URL ||
      process.env.REACT_APP_MASTER_DASHBOARD_URL;
    if (cra != null && String(cra).trim() !== "") {
      const trimmed = String(cra).trim().replace(/\/+$/, "");
      return trimmed.endsWith("/login") ? trimmed : `${trimmed}/login`;
    }
  }
  return `${DEFAULT_MASTER_URL}/login`;
}

export function getHseLoginUrl() {
  return readEnvLoginUrl();
}

export function redirectToHseLogin() {
  if (typeof window !== "undefined") {
    window.location.replace(getHseLoginUrl());
  }
}

export function getMasterDashboardUrl() {
  const login = getHseLoginUrl();
  return login.replace(/\/login\/?$/, "") || DEFAULT_MASTER_URL;
}
