const DEFAULT_API_BASE_URL = 'http://localhost:3000/api';

const normalizeHttpUrl = (value?: string | null): string | null => {
  const trimmed = String(value || '').trim();
  if (!trimmed) return null;

  try {
    const parsed = new URL(trimmed);
    return `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, '');
  } catch {
    return null;
  }
};

export const getConfiguredApiBaseUrl = (): string => {
  const explicitApiUrl = normalizeHttpUrl(process.env.EXPO_PUBLIC_API_URL);
  if (explicitApiUrl) return explicitApiUrl;

  const backendBaseUrl = normalizeHttpUrl(
    process.env.EXPO_PUBLIC_BACKEND_URL || process.env.EXPO_PUBLIC_PAYMENT_SERVER_URL,
  );
  if (backendBaseUrl) {
    return backendBaseUrl.endsWith('/api') ? backendBaseUrl : `${backendBaseUrl}/api`;
  }

  return DEFAULT_API_BASE_URL;
};

export const getConfiguredBackendRootUrl = (): string => {
  const explicitApiUrl = normalizeHttpUrl(process.env.EXPO_PUBLIC_API_URL);
  if (explicitApiUrl) {
    return explicitApiUrl.endsWith('/api')
      ? explicitApiUrl.slice(0, -4).replace(/\/+$/, '')
      : explicitApiUrl;
  }

  return normalizeHttpUrl(
    process.env.EXPO_PUBLIC_BACKEND_URL || process.env.EXPO_PUBLIC_PAYMENT_SERVER_URL,
  ) || '';
};

export const getConfiguredAssetBaseUrl = (): string => {
  const apiBaseUrl = getConfiguredApiBaseUrl();

  try {
    const parsed = new URL(apiBaseUrl);
    const pathname = parsed.pathname.replace(/\/+$/, '');
    const assetPath = pathname.endsWith('/api')
      ? pathname.slice(0, -4)
      : pathname;
    return `${parsed.origin}${assetPath}`.replace(/\/+$/, '');
  } catch {
    return 'http://localhost:3000';
  }
};
