// 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';

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

    late MockFormRepository formRepository;
    late AuthenticationRepository<int> authenticationRepository;

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

      when(
        () => authenticationRepository.sendPasswordResetEmail(
          email: any(named: 'email'),
        ),
      ).thenAnswer((_) async => const Ok(null));

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

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

    test('initial state is pure', () {
      expect(
        PasswordResetCubit(
          authenticationRepository: authenticationRepository,
        ).state,
        PasswordResetState(form: form),
      );
    });

    group('emailChanged', () {
      blocTest<PasswordResetCubit<int>, PasswordResetState>(
        'emits [invalid] when email is invalid',
        build: () => PasswordResetCubit(
          authenticationRepository: authenticationRepository,
        ),
        act: (cubit) => cubit.emailChanged(invalidEmailString),
        expect: () => <PasswordResetState>[
          PasswordResetState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(invalidEmailString),
                ),
              ],
              name: AuthFormName.passwordResetForm,
            ),
            status: FormStatus.invalid,
          ),
        ],
      );

      blocTest<PasswordResetCubit<int>, PasswordResetState>(
        'emits [valid] when email is valid',
        setUp: () {
          when(
            () => formRepository.accessForm(AuthFormName.passwordResetForm),
          ).thenAnswer(
            (_) => WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.pure(),
                ),
              ],
              name: AuthFormName.passwordResetForm,
            ),
          );
        },
        build: () => PasswordResetCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => PasswordResetState(
          form: WyattFormImpl(
            [
              FormInput(
                AuthFormField.email,
                const Email.pure(),
              ),
            ],
            name: AuthFormName.passwordResetForm,
          ),
          status: FormStatus.invalid,
        ),
        act: (cubit) => cubit.emailChanged(validEmailString),
        expect: () => <PasswordResetState>[
          PasswordResetState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
              ],
              name: AuthFormName.passwordResetForm,
            ),
            status: FormStatus.valid,
          ),
        ],
      );
    });

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

      blocTest<PasswordResetCubit<int>, PasswordResetState>(
        'calls sendPasswordResetEmail with correct email',
        setUp: () {
          when(
            () => formRepository.accessForm(AuthFormName.passwordResetForm),
          ).thenAnswer(
            (_) => WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
              ],
              name: AuthFormName.passwordResetForm,
            ),
          );
        },
        build: () => PasswordResetCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => PasswordResetState(
          form: WyattFormImpl(
            [
              FormInput(
                AuthFormField.email,
                const Email.dirty(validEmailString),
              ),
            ],
            name: AuthFormName.passwordResetForm,
          ),
          status: FormStatus.valid,
        ),
        act: (cubit) => cubit.submit(),
        verify: (_) {
          verify(
            () => authenticationRepository.sendPasswordResetEmail(
              email: validEmailString,
            ),
          ).called(1);
        },
      );

      blocTest<PasswordResetCubit<int>, PasswordResetState>(
        'emits [submissionInProgress, submissionSuccess] '
        'when sendPasswordResetEmail succeeds',
        setUp: () {
          when(
            () => formRepository.accessForm(AuthFormName.passwordResetForm),
          ).thenAnswer(
            (_) => WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
              ],
              name: AuthFormName.passwordResetForm,
            ),
          );
        },
        build: () => PasswordResetCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => PasswordResetState(
          form: WyattFormImpl(
            [
              FormInput(
                AuthFormField.email,
                const Email.dirty(validEmailString),
              ),
            ],
            name: AuthFormName.passwordResetForm,
          ),
          status: FormStatus.valid,
        ),
        act: (cubit) => cubit.submit(),
        expect: () => <PasswordResetState>[
          PasswordResetState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
              ],
              name: AuthFormName.passwordResetForm,
            ),
            status: FormStatus.submissionInProgress,
          ),
          PasswordResetState(
            form: WyattFormImpl(
              [
                FormInput(
                  AuthFormField.email,
                  const Email.dirty(validEmailString),
                ),
              ],
              name: AuthFormName.passwordResetForm,
            ),
            status: FormStatus.submissionSuccess,
          )
        ],
      );

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