import 'dart:async';

import 'package:flutter_test/flutter_test.dart';
import 'package:formz/formz.dart';
import 'package:mocktail/mocktail.dart';
import 'package:social_app/features/auth/data/auth_repository.dart';
import 'package:social_app/features/auth/presentation/cubits/reset_password_cubit.dart';

class MockAuthRepository extends Mock implements AuthRepository {}

void main() {
  late ResetPasswordCubit cubit;
  late MockAuthRepository mockRepository;

  setUp(() {
    mockRepository = MockAuthRepository();
    cubit = ResetPasswordCubit(mockRepository);
  });

  tearDown(() async {
    await cubit.close();
  });

  test(
    'sendCode enters countdown immediately and prevents duplicate clicks',
    () async {
      final completer = Completer<void>();
      when(
        () => mockRepository.requestPasswordReset(any()),
      ).thenAnswer((_) => completer.future);

      cubit.emailChanged('test@example.com');

      final firstRequest = cubit.sendCode();
      await Future<void>.delayed(Duration.zero);

      expect(cubit.state.status, FormzSubmissionStatus.inProgress);
      expect(cubit.state.codeSent, isTrue);
      expect(cubit.state.resendCountdown, 60);

      await cubit.sendCode();
      verify(
        () => mockRepository.requestPasswordReset('test@example.com'),
      ).called(1);

      completer.complete();
      await firstRequest;
    },
  );

  test('sendCode failure cancels countdown and restores retry state', () async {
    when(
      () => mockRepository.requestPasswordReset(any()),
    ).thenThrow(Exception('network error'));

    cubit.emailChanged('test@example.com');

    await cubit.sendCode();

    expect(cubit.state.status, FormzSubmissionStatus.failure);
    expect(cubit.state.codeSent, isFalse);
    expect(cubit.state.resendCountdown, 0);
    expect(cubit.state.errorMessage, '网络错误，请稍后重试');
  });
}
