// Confirms Firebase Phone Auth actually dispatches an OTP SMS.
//
// This must run on a real device or emulator with Google Play services —
// `flutter_test`'s headless VM has no platform channels, so FirebaseAuth
// would throw MissingPluginException there. Each run sends one real, billed
// SMS (Blaze plan) to the hardcoded number below.
//
// Run with a device attached:
//   flutter test integration_test/otp_send_test.dart -d <device-id>
// (list device ids with `flutter devices`)
import 'dart:async';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';

void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  testWidgets('Firebase dispatches OTP SMS to a real phone number',
      (tester) async {
    await Firebase.initializeApp();

    const phoneNumber = '+916374946729';
    final completer = Completer<String>();

    await FirebaseAuth.instance.verifyPhoneNumber(
      phoneNumber: phoneNumber,
      timeout: const Duration(seconds: 60),
      verificationCompleted: (PhoneAuthCredential credential) {
        if (!completer.isCompleted) {
          completer.complete('verificationCompleted (device auto-verified)');
        }
      },
      verificationFailed: (FirebaseAuthException e) {
        if (!completer.isCompleted) {
          completer.completeError('verificationFailed: ${e.code} — ${e.message}');
        }
      },
      codeSent: (String verificationId, int? resendToken) {
        if (!completer.isCompleted) {
          completer.complete('codeSent (verificationId: $verificationId)');
        }
      },
      codeAutoRetrievalTimeout: (String verificationId) {
        if (!completer.isCompleted) {
          completer.complete(
              'codeAutoRetrievalTimeout (verificationId: $verificationId) — request was accepted, auto-retrieval just timed out');
        }
      },
    );

    final result = await completer.future.timeout(
      const Duration(seconds: 45),
      onTimeout: () => throw TimeoutException(
          'No callback fired within 45s — check phone provider is enabled, '
          'Blaze billing is active, and SHA-1/SHA-256 fingerprints are '
          'registered in Firebase console.'),
    );

    debugPrint('OTP SEND RESULT: $result');
    expect(result, isNotEmpty);
    expect(result, isNot(contains('verificationFailed')));
  });
}
