const DEV_DEFAULT_URL = "https://benell.maliountech.com.mx";

function normalizeUrl(raw: string | undefined): string | null {
  if (!raw) {
    return null;
  }

  try {
    const parsed = new URL(raw);

    if (parsed.hostname === "0.0.0.0" || parsed.hostname === "::" || parsed.hostname === "[::]") {
      parsed.hostname = "benell.maliountech.com.mx";
      parsed.protocol = "https:";
    }

    return parsed.toString().replace(/\/$/, "");
  } catch {
    return null;
  }
}

export function getBaseAppUrl() {
  return normalizeUrl(process.env.APP_URL) || normalizeUrl(process.env.NEXTAUTH_URL) || DEV_DEFAULT_URL;
}
