const _compileTimeEnv = {
  'APP_ENV': String.fromEnvironment('APP_ENV'),
  'BACKEND_URL': String.fromEnvironment('BACKEND_URL'),
  'CLIENT_LOG_DEBUG': String.fromEnvironment('CLIENT_LOG_DEBUG'),
  'USERFRONT_DEBUG_LOG': String.fromEnvironment('USERFRONT_DEBUG_LOG'),
  'USERFRONT_URL': String.fromEnvironment('USERFRONT_URL'),
};

String runtimeOriginFallback() {
  try {
    final origin = Uri.base.origin;
    if (origin.isNotEmpty && origin != 'null') {
      return origin;
    }
  } catch (_) {}
  return '';
}

String envOrDefault(String key, String fallback) {
  final compileTimeValue = _compileTimeEnv[key];
  if (compileTimeValue != null && compileTimeValue.trim().isNotEmpty) {
    return compileTimeValue;
  }
  return fallback;
}

String sanitizedUrl(String value) {
  return value.replaceAll(r'$', '').trim().replaceAll(RegExp(r'/$'), '');
}

String runtimeBackendUrl() {
  return sanitizedUrl(envOrDefault('BACKEND_URL', runtimeOriginFallback()));
}

String runtimeUserfrontUrl() {
  return sanitizedUrl(envOrDefault('USERFRONT_URL', runtimeOriginFallback()));
}
