// 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() {
  const String invalidEmailString = 'invalid';

  const String validEmailString = 'test@gmail.com';

  const String invalidPasswordString = 'invalid';

  const String validPasswordString = 't0pS3cret1234';

  group('SignInCubit', () {
    final MockAccount account = MockAccount();
    final WyattForm form = WyattFormImpl(
      [
        FormInput(AuthFormField.email, const Email.pure()),
        FormInput(AuthFormField.password, const Password.pure())
      ],
      name: AuthFormName.signInForm,
    );

    late MockFormRepository formRepository;
    late AuthenticationRepository<int> authenticationRepository;

    setUp(() {
      authenticationRepository = MockAuthenticationRepository();
      formRepository = MockFormRepository();

      when(
        () => authenticationRepository.signInWithEmailAndPassword(
          email: any(named: 'email'),
          password: any(named: 'password'),
        ),
      ).thenAnswer((_) async => Ok(account));

      when(
        () => authenticationRepository.signInAnonymously(),
      ).thenAnswer((_) async => Ok(account));

      when(
        () => authenticationRepository.formRepository,
      ).thenAnswer((_) => formRepository);

      when(
        () => formRepository.accessForm(AuthFormName.signInForm),
      ).thenAnswer((_) => form);
    });

    test('initial state is SignInState', () {
      expect(
        SignInCubit(
          authenticationRepository: authenticationRepository,
        ).state,
        SignInState(form: form),
      );
    });

    group('emailChanged', () {
      blocTest<SignInCubit<int>, SignInState>(
        'emits [invalid] when email/password are invalid',
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        act: (cubit) => cubit.emailChanged(invalidEmailString),
        expect: () => <SignInState>[
          SignInState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(invalidEmailString),
                ),
                FormInput(AuthFormField.password, const Password.pure())
              ],
              name: AuthFormName.signInForm,
            ),
            status: FormStatus.invalid,
          ),
        ],
      );

      blocTest<SignInCubit<int>, SignInState>(
        'emits [valid] when email/password are valid',
        setUp: () {
          when(
            () => formRepository.accessForm(AuthFormName.signInForm),
          ).thenAnswer(
            (_) => WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.pure(),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
          );
        },
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignInState(
          form: WyattFormImpl(
            [
              FormInput(
                AuthFormField.email,
                const Email.pure(),
              ),
              FormInput(
                AuthFormField.password,
                const Password.dirty(validPasswordString),
              )
            ],
            name: AuthFormName.signInForm,
          ),
          status: FormStatus.invalid,
        ),
        act: (cubit) => cubit.emailChanged(validEmailString),
        expect: () => <SignInState>[
          SignInState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
            status: FormStatus.valid,
          ),
        ],
      );
    });

    group('passwordChanged', () {
      blocTest<SignInCubit<int>, SignInState>(
        'emits [invalid] when email/password are invalid',
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        act: (cubit) => cubit.passwordChanged(invalidPasswordString),
        expect: () => <SignInState>[
          SignInState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.pure(),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(invalidPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
            status: FormStatus.invalid,
          ),
        ],
      );

      blocTest<SignInCubit<int>, SignInState>(
        'emits [valid] when email/password are valid',
        setUp: () {
          when(
            () => formRepository.accessForm(AuthFormName.signInForm),
          ).thenAnswer(
            (_) => WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.pure(),
                )
              ],
              name: AuthFormName.signInForm,
            ),
          );
        },
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignInState(
          form: WyattFormImpl(
            [
              FormInput(
                AuthFormField.email,
                const Email.dirty(validEmailString),
              ),
              FormInput(
                AuthFormField.password,
                const Password.pure(),
              )
            ],
            name: AuthFormName.signInForm,
          ),
          status: FormStatus.invalid,
        ),
        act: (cubit) => cubit.passwordChanged(validPasswordString),
        expect: () => <SignInState>[
          SignInState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
            status: FormStatus.valid,
          ),
        ],
      );
    });

    group('signInWithEmailAndPassword()', () {
      blocTest<SignInCubit<int>, SignInState>(
        'does nothing when status is not validated',
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        act: (cubit) => cubit.signInWithEmailAndPassword(),
        expect: () => const <SignInState>[],
      );

      blocTest<SignInCubit<int>, SignInState>(
        'does nothing when status is submitInProgress',
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignInState(
          form: WyattFormImpl(
            [
              FormInput(
                AuthFormField.email,
                const Email.dirty(validEmailString),
              ),
              FormInput(
                AuthFormField.password,
                const Password.dirty(validPasswordString),
              )
            ],
            name: AuthFormName.signInForm,
          ),
          status: FormStatus.submissionInProgress,
        ),
        act: (cubit) => cubit.signInWithEmailAndPassword(),
        expect: () => const <SignInState>[],
      );

      blocTest<SignInCubit<int>, SignInState>(
        'calls signInWithEmailAndPassword with correct email/password',
        setUp: () {
          when(
            () => formRepository.accessForm(AuthFormName.signInForm),
          ).thenAnswer(
            (_) => WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
          );
        },
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignInState(
          form: WyattFormImpl(
            [
              FormInput(
                AuthFormField.email,
                const Email.dirty(validEmailString),
              ),
              FormInput(
                AuthFormField.password,
                const Password.dirty(validPasswordString),
              )
            ],
            name: AuthFormName.signInForm,
          ),
          status: FormStatus.valid,
        ),
        act: (cubit) => cubit.signInWithEmailAndPassword(),
        verify: (_) {
          verify(
            () => authenticationRepository.signInWithEmailAndPassword(
              email: validEmailString,
              password: validPasswordString,
            ),
          ).called(1);
        },
      );

      blocTest<SignInCubit<int>, SignInState>(
        'emits [submissionInProgress, submissionSuccess] '
        'when signInWithEmailAndPassword succeeds',
        setUp: () {
          when(
            () => formRepository.accessForm(AuthFormName.signInForm),
          ).thenAnswer(
            (_) => WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
          );
        },
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignInState(
          form: WyattFormImpl(
            [
              FormInput(
                AuthFormField.email,
                const Email.dirty(validEmailString),
              ),
              FormInput(
                AuthFormField.password,
                const Password.dirty(validPasswordString),
              )
            ],
            name: AuthFormName.signInForm,
          ),
          status: FormStatus.valid,
        ),
        act: (cubit) => cubit.signInWithEmailAndPassword(),
        expect: () => <SignInState>[
          SignInState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
            status: FormStatus.submissionInProgress,
          ),
          SignInState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
            status: FormStatus.submissionSuccess,
          )
        ],
      );

      blocTest<SignInCubit<int>, SignInState>(
        'emits [submissionInProgress, submissionFailure] '
        'when signInWithEmailAndPassword fails',
        setUp: () {
          when(
            () => authenticationRepository.signInWithEmailAndPassword(
              email: any(named: 'email'),
              password: any(named: 'password'),
            ),
          ).thenAnswer((_) async => Err(ServerException()));
          when(
            () => formRepository.accessForm(AuthFormName.signInForm),
          ).thenAnswer(
            (_) => WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
          );
        },
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignInState(
          form: WyattFormImpl(
            [
              FormInput(
                AuthFormField.email,
                const Email.dirty(validEmailString),
              ),
              FormInput(
                AuthFormField.password,
                const Password.dirty(validPasswordString),
              )
            ],
            name: AuthFormName.signInForm,
          ),
          status: FormStatus.valid,
        ),
        act: (cubit) => cubit.signInWithEmailAndPassword(),
        expect: () => <SignInState>[
          SignInState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
            status: FormStatus.submissionInProgress,
          ),
          SignInState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
            status: FormStatus.submissionFailure,
          )
        ],
      );
    });

    group('signInAnonymously()', () {
      blocTest<SignInCubit<int>, SignInState>(
        'does nothing when status is submitInProgress',
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignInState(
          form: WyattFormImpl(
            [
              FormInput(
                AuthFormField.email,
                const Email.dirty(validEmailString),
              ),
              FormInput(
                AuthFormField.password,
                const Password.dirty(validPasswordString),
              )
            ],
            name: AuthFormName.signInForm,
          ),
          status: FormStatus.submissionInProgress,
        ),
        act: (cubit) => cubit.signInAnonymously(),
        expect: () => const <SignInState>[],
      );

      blocTest<SignInCubit<int>, SignInState>(
        'calls signInAnonymously',
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        act: (cubit) => cubit.signInAnonymously(),
        verify: (_) {
          verify(
            () => authenticationRepository.signInAnonymously(),
          ).called(1);
        },
      );

      blocTest<SignInCubit<int>, SignInState>(
        'emits [submissionInProgress, submissionSuccess] '
        'when signInAnonymously succeeds',
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignInState(
          form: WyattFormImpl(
            [
              FormInput(
                AuthFormField.email,
                const Email.dirty(validEmailString),
              ),
              FormInput(
                AuthFormField.password,
                const Password.dirty(validPasswordString),
              )
            ],
            name: AuthFormName.signInForm,
          ),
          status: FormStatus.valid,
        ),
        act: (cubit) => cubit.signInAnonymously(),
        expect: () => <SignInState>[
          SignInState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
            status: FormStatus.submissionInProgress,
          ),
          SignInState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
            status: FormStatus.submissionSuccess,
          )
        ],
      );

      blocTest<SignInCubit<int>, SignInState>(
        'emits [submissionInProgress, submissionFailure] '
        'when signInAnonymously fails',
        setUp: () {
          when(
            () => authenticationRepository.signInAnonymously(),
          ).thenAnswer((_) async => Err(ServerException()));
        },
        build: () => SignInCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignInState(
          form: WyattFormImpl(
            [
              FormInput(
                AuthFormField.email,
                const Email.dirty(validEmailString),
              ),
              FormInput(
                AuthFormField.password,
                const Password.dirty(validPasswordString),
              )
            ],
            name: AuthFormName.signInForm,
          ),
          status: FormStatus.valid,
        ),
        act: (cubit) => cubit.signInAnonymously(),
        expect: () => <SignInState>[
          SignInState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
            status: FormStatus.submissionInProgress,
          ),
          SignInState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
                FormInput(
                  AuthFormField.password,
                  const Password.dirty(validPasswordString),
                )
              ],
              name: AuthFormName.signInForm,
            ),
            status: FormStatus.submissionFailure,
          )
        ],
      );
    });
  });
}
