import 'package:flutter_dotenv/flutter_dotenv.dart';

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

String runtimeOriginFallback() {
  try {
    final origin = Uri.base.origin;
    if (origin.isNotEmpty && origin != 'null') {
      return origin;
    }
  } catch (_) {}
  return 'https://sso-test.hmac.kr';
}

String envOrDefault(String key, String fallback) {
  if (dotenv.isInitialized) {
    final value = dotenv.env[key];
    if (value != null && value.trim().isNotEmpty) {
      return value;
    }
  }

  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()));
}
