const DEFAULT_PORTAL_URL = 'https://portal.sankofa.nexus';
const DEFAULT_PARTNER_PROGRAMS_URL = 'https://phoenix.sankofa.nexus/marketplace';

function normalizeBaseUrl(value: string | undefined, fallback: string): string {
  const candidate = value?.trim();
  if (!candidate) return fallback;

  try {
    return new URL(candidate).toString().replace(/\/$/, '');
  } catch {
    return fallback;
  }
}

function appendPath(baseUrl: string, path = '/'): string {
  const normalizedPath = path.startsWith('/') ? path : `/${path}`;
  const url = new URL(baseUrl);
  url.pathname = normalizedPath;
  url.search = '';
  url.hash = '';
  return url.toString();
}

export function getPortalUrl(path = '/'): string {
  const baseUrl = normalizeBaseUrl(process.env.NEXT_PUBLIC_PORTAL_URL, DEFAULT_PORTAL_URL);
  return appendPath(baseUrl, path);
}

export function getAdminPortalUrl(): string {
  return getPortalUrl('/admin');
}

export function getDeveloperPortalUrl(): string {
  return getPortalUrl('/developer');
}

export function getPartnerPortalUrl(): string {
  return getPortalUrl('/partner');
}

export function getPartnerProgramsUrl(path = '/marketplace'): string {
  const baseUrl = normalizeBaseUrl(
    process.env.NEXT_PUBLIC_PARTNER_PROGRAMS_URL,
    DEFAULT_PARTNER_PROGRAMS_URL
  );
  return appendPath(baseUrl, path);
}
