import 'package:flutter_test/flutter_test.dart';
import 'package:userfront/core/services/runtime_env.dart';

const _expectedBackendUrl = String.fromEnvironment('BACKEND_URL');
const _expectedUserfrontUrl = String.fromEnvironment('USERFRONT_URL');

void main() {
  group('runtime env compile-time defines', () {
    test('runtime fallback is empty outside a browser origin', () {
      expect(runtimeOriginFallback(), isEmpty);
    });

    test(
      'BACKEND_URL dart-define overrides runtime origin fallback when set',
      () {
        if (_expectedBackendUrl.isEmpty) {
          expect(runtimeBackendUrl(), runtimeOriginFallback());
          return;
        }

        expect(runtimeBackendUrl(), sanitizedUrl(_expectedBackendUrl));
      },
    );

    test(
      'USERFRONT_URL dart-define overrides runtime origin fallback when set',
      () {
        if (_expectedUserfrontUrl.isEmpty) {
          expect(runtimeUserfrontUrl(), runtimeOriginFallback());
          return;
        }

        expect(runtimeUserfrontUrl(), sanitizedUrl(_expectedUserfrontUrl));
      },
    );

    test('dart-define URLs are sanitized', () {
      if (_expectedBackendUrl.isEmpty || _expectedUserfrontUrl.isEmpty) {
        return;
      }

      expect(runtimeBackendUrl(), isNot(endsWith('/')));
      expect(runtimeUserfrontUrl(), isNot(endsWith('/')));
    });

    test(
      'sanitizedUrl removes dollar signs, whitespace, and trailing slash',
      () {
        expect(
          sanitizedUrl('  https://example.test/path/\$  '),
          'https://example.test/path',
        );
      },
    );
  });
}
