import 'package:flutter_test/flutter_test.dart';
import 'package:gametime/application/application.dart';
import 'package:gametime/infrastructure/remote/remote.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';

void main() {
  test(
    'defaultBaseUrl keeps localhost outside Android without env override',
    () {
      expect(
        HttpApiClient.defaultBaseUrlFor(isAndroid: false),
        'http://localhost:8080',
      );
    },
  );

  test('defaultBaseUrl uses Android emulator host without env override', () {
    expect(
      HttpApiClient.defaultBaseUrlFor(isAndroid: true),
      'http://10.0.2.2:8090',
    );
  });

  test('defaultBaseUrl keeps env override on Android', () {
    expect(
      HttpApiClient.defaultBaseUrlFor(
        isAndroid: true,
        configuredBaseUrl: ' http://192.168.1.75:8090 ',
      ),
      'http://192.168.1.75:8090',
    );
  });

  test('postJson maps server errors to server failure', () async {
    final client = HttpApiClient(
      baseUrl: Uri.parse('http://api.example.test'),
      client: MockClient(
        (_) async => http.Response('{"error":"internal"}', 500),
      ),
    );

    await expectLater(
      client.postJson('/auth/login'),
      throwsA(
        isA<RemoteAuthException>()
            .having(
              (error) => error.failure,
              'failure',
              RemoteAuthFailure.server,
            )
            .having((error) => error.message, 'message', 'internal'),
      ),
    );
  });

  test('postJson maps transport failures to network failure', () async {
    final client = HttpApiClient(
      baseUrl: Uri.parse('http://api.example.test'),
      client: MockClient((_) async => throw http.ClientException('refused')),
    );

    await expectLater(
      client.postJson('/auth/login'),
      throwsA(
        isA<RemoteAuthException>()
            .having(
              (error) => error.failure,
              'failure',
              RemoteAuthFailure.network,
            )
            .having((error) => error.message, 'message', 'refused'),
      ),
    );
  });
}
