'use client';

const AUTH_PORTAL_URL = process.env.NEXT_PUBLIC_AUTH_PORTAL_URL?.trim();
const AUTH_PORTAL_PORT = process.env.NEXT_PUBLIC_AUTH_PORTAL_PORT?.trim() || '3081';

function normalizeBaseUrl(value?: string | null): string | null {
  const trimmed = value?.trim();
  if (!trimmed) return null;
  return trimmed.replace(/\/+$/, '');
}

function getPortalBaseUrl(): string {
  const explicit = normalizeBaseUrl(AUTH_PORTAL_URL);
  if (explicit) return explicit;
  if (typeof window !== 'undefined') {
    const url = new URL(window.location.origin);
    url.port = AUTH_PORTAL_PORT;
    return normalizeBaseUrl(url.toString()) || window.location.origin;
  }
  return `http://127.0.0.1:${AUTH_PORTAL_PORT}`;
}

export function buildAuthPortalUrl(path: '/login' | '/register', nextPath?: string | null): string {
  const url = new URL(path, `${getPortalBaseUrl()}/`);
  const nextValue = nextPath?.trim();
  if (nextValue) {
    url.searchParams.set('next', nextValue);
  }
  return url.toString();
}

