// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
import 'package:wyatt_authentication_bloc/wyatt_authentication_bloc.dart';
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';

class MockAuthenticationRepository extends Mock
    implements AuthenticationRepository<int> {}

class MockAuthenticationCubit extends Mock implements AuthenticationCubit<int> {
}

class MockAccount extends Mock implements Account {}

class MockFormRepository extends Mock implements FormRepository {}

void main() {
  group('EmailVerificationCubit<T>', () {
    late MockAccount account;
    late AuthenticationRepository<int> authenticationRepository;

    setUp(() {
      authenticationRepository = MockAuthenticationRepository();
      when(
        () => authenticationRepository.getAccount(),
      ).thenAnswer((_) async => Ok(account));

      when(
        () => authenticationRepository.refresh(),
      ).thenAnswer((_) async => const Ok(null));

      account = MockAccount();
      when(
        () => account.emailVerified,
      ).thenAnswer((_) => true);
    });

    test('initial state is `false`', () {
      expect(
        EmailVerificationCubit<int>(
          authenticationRepository: authenticationRepository,
        ).state,
        const EmailVerificationState(),
      );
    });

    group('SendVerificationEmail', () {
      blocTest<EmailVerificationCubit<int>, EmailVerificationState>(
        'invokes sendEmailVerification,',
        setUp: () {
          when(() => authenticationRepository.sendEmailVerification())
              .thenAnswer((_) async => const Ok(null));
        },
        build: () => EmailVerificationCubit(
          authenticationRepository: authenticationRepository,
        ),
        act: (cubit) => cubit.sendEmailVerification(),
        verify: (_) {
          verify(() => authenticationRepository.sendEmailVerification())
              .called(1);
        },
      );

      blocTest<EmailVerificationCubit<int>, EmailVerificationState>(
        'emits success',
        setUp: () {
          when(() => authenticationRepository.sendEmailVerification())
              .thenAnswer((_) async => const Ok(null));
        },
        build: () => EmailVerificationCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => const EmailVerificationState(),
        act: (cubit) => cubit.sendEmailVerification(),
        expect: () => [
          const EmailVerificationState(
            status: FormStatus.submissionInProgress,
          ),
          const EmailVerificationState(
            status: FormStatus.submissionSuccess,
          )
        ],
      );

      blocTest<EmailVerificationCubit<int>, EmailVerificationState>(
        'emits failure',
        setUp: () {
          when(() => authenticationRepository.sendEmailVerification())
              .thenAnswer((_) async => Err(ServerException('erreur')));
        },
        build: () => EmailVerificationCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => const EmailVerificationState(),
        act: (cubit) => cubit.sendEmailVerification(),
        expect: () => [
          const EmailVerificationState(
            status: FormStatus.submissionInProgress,
          ),
          const EmailVerificationState(
            errorMessage: 'erreur',
            status: FormStatus.submissionFailure,
          )
        ],
      );
    });

    group('CheckEmailVerification', () {
      blocTest<EmailVerificationCubit<int>, EmailVerificationState>(
        'invokes refresh,',
        setUp: () {
          when(
            () => authenticationRepository.refresh(),
          ).thenAnswer((_) async => const Ok(null));
        },
        build: () => EmailVerificationCubit(
          authenticationRepository: authenticationRepository,
        ),
        act: (cubit) => cubit.checkEmailVerification(),
        verify: (_) {
          verify(() => authenticationRepository.refresh()).called(1);
        },
      );

      blocTest<EmailVerificationCubit<int>, EmailVerificationState>(
        'invokes emailVerified,',
        setUp: () {
          when(
            () => authenticationRepository.refresh(),
          ).thenAnswer((_) async => const Ok(null));
          when(() => account.emailVerified).thenAnswer((_) => false);
        },
        build: () => EmailVerificationCubit(
          authenticationRepository: authenticationRepository,
        ),
        act: (cubit) => cubit.checkEmailVerification(),
        verify: (_) {
          verify(() => account.emailVerified).called(1);
        },
      );

      blocTest<EmailVerificationCubit<int>, EmailVerificationState>(
        'emits success with true if verified',
        setUp: () {
          when(() => authenticationRepository.refresh())
              .thenAnswer((_) async => const Ok(null));
        },
        build: () => EmailVerificationCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => const EmailVerificationState(),
        act: (cubit) => cubit.checkEmailVerification(),
        expect: () => [
          const EmailVerificationState(
            status: FormStatus.submissionInProgress,
          ),
          const EmailVerificationState(
            isVerified: true,
            status: FormStatus.submissionSuccess,
          )
        ],
      );

      blocTest<EmailVerificationCubit<int>, EmailVerificationState>(
        'emits success with false if not verified',
        setUp: () {
          when(() => authenticationRepository.refresh())
              .thenAnswer((_) async => const Ok(null));
          when(() => account.emailVerified).thenAnswer((_) => false);
        },
        build: () => EmailVerificationCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => const EmailVerificationState(),
        act: (cubit) => cubit.checkEmailVerification(),
        expect: () => [
          const EmailVerificationState(
            status: FormStatus.submissionInProgress,
          ),
          const EmailVerificationState(
            status: FormStatus.submissionSuccess,
          )
        ],
      );

      blocTest<EmailVerificationCubit<int>, EmailVerificationState>(
        'emits failure on refresh error',
        setUp: () {
          when(() => authenticationRepository.refresh())
              .thenAnswer((_) async => Err(ServerException('erreur')));
        },
        build: () => EmailVerificationCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => const EmailVerificationState(),
        act: (cubit) => cubit.checkEmailVerification(),
        expect: () => [
          const EmailVerificationState(
            status: FormStatus.submissionInProgress,
          ),
          const EmailVerificationState(
            errorMessage: 'erreur',
            status: FormStatus.submissionFailure,
          )
        ],
      );

      blocTest<EmailVerificationCubit<int>, EmailVerificationState>(
        'emits failure on get account error',
        setUp: () {
          when(() => authenticationRepository.getAccount())
              .thenAnswer((_) async => Err(ServerException('erreur')));
        },
        build: () => EmailVerificationCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => const EmailVerificationState(),
        act: (cubit) => cubit.checkEmailVerification(),
        expect: () => [
          const EmailVerificationState(
            status: FormStatus.submissionInProgress,
          ),
          const EmailVerificationState(
            errorMessage: 'erreur',
            status: FormStatus.submissionFailure,
          )
        ],
      );
    });
  });
}
