import 'package:flutter_test/flutter_test.dart';
import 'package:nomadcode_app/src/integrations/proto_socket/proto_socket_endpoint_config.dart';

void main() {
  group('ProtoSocketEndpointConfig defaults', () {
    test('defaults path to "/" when not provided', () {
      const config = ProtoSocketEndpointConfig(
        host: 'core.example.com',
        port: 443,
        secure: true,
      );
      expect(config.path, equals('/'));
      expect(config.enabled, isFalse);
      expect(config.heartbeatIntervalSeconds, equals(30));
      expect(config.heartbeatWaitSeconds, equals(60));
    });

    test('scheme selects wss when secure, ws otherwise', () {
      const secureConfig = ProtoSocketEndpointConfig(
        host: 'core.example.com',
        port: 443,
        secure: true,
      );
      const plainConfig = ProtoSocketEndpointConfig(
        host: 'core.example.com',
        port: 8080,
        secure: false,
      );
      expect(secureConfig.scheme, equals('wss'));
      expect(plainConfig.scheme, equals('ws'));
      final uri = secureConfig.toUri();
      expect(uri.scheme, equals('wss'));
      expect(uri.host, equals('core.example.com'));
      expect(uri.port, equals(443));
    });
  });

  group('ProtoSocketEndpointConfig.fromEnv', () {
    test('returns null when PROTO_SOCKET_HOST is missing or empty', () {
      expect(ProtoSocketEndpointConfig.fromEnv(const {}), isNull);
      expect(
        ProtoSocketEndpointConfig.fromEnv(const {'PROTO_SOCKET_HOST': '  '}),
        isNull,
      );
    });

    test('parses full env map with explicit values', () {
      final config = ProtoSocketEndpointConfig.fromEnv(const {
        'PROTO_SOCKET_HOST': 'core.example.com',
        'PROTO_SOCKET_PORT': '9443',
        'PROTO_SOCKET_SECURE': 'true',
        'PROTO_SOCKET_PATH': 'socket',
        'PROTO_SOCKET_HEARTBEAT_INTERVAL_SECONDS': '15',
        'PROTO_SOCKET_HEARTBEAT_WAIT_SECONDS': '45',
        'PROTO_SOCKET_ENABLED': 'true',
      });
      expect(config, isNotNull);
      expect(config!.host, equals('core.example.com'));
      expect(config.port, equals(9443));
      expect(config.secure, isTrue);
      expect(config.path, equals('/socket'));
      expect(config.heartbeatIntervalSeconds, equals(15));
      expect(config.heartbeatWaitSeconds, equals(45));
      expect(config.enabled, isTrue);
    });

    test('falls back to default port based on secure flag', () {
      final secureConfig = ProtoSocketEndpointConfig.fromEnv(const {
        'PROTO_SOCKET_HOST': 'core.example.com',
        'PROTO_SOCKET_SECURE': 'true',
      });
      final plainConfig = ProtoSocketEndpointConfig.fromEnv(const {
        'PROTO_SOCKET_HOST': 'core.example.com',
        'PROTO_SOCKET_SECURE': 'false',
      });
      expect(secureConfig!.port, equals(443));
      expect(plainConfig!.port, equals(80));
    });
  });
}
