// 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('SignUpCubit', () {
    final MockAccount account = MockAccount();
    final WyattForm form = WyattFormImpl(
      [
        FormInput(AuthFormField.email, const Email.pure()),
        FormInput(AuthFormField.password, const Password.pure())
      ],
      name: AuthFormName.signUpForm,
    );

    late MockFormRepository formRepository;
    late AuthenticationRepository<int> authenticationRepository;

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

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

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

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

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

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

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

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

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

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

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

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

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

    group('update', () {
      final inputsA = <
          FormInput<dynamic, FormInputValidator<dynamic, ValidationError>,
              dynamic>>[
        FormInput(AuthFormField.email, const Email.pure()),
        FormInput(AuthFormField.password, const Password.pure())
      ];

      final inputsB = <
          FormInput<dynamic, FormInputValidator<dynamic, ValidationError>,
              dynamic>>[
        FormInput('name', const Name.pure()),
        FormInput('phone', const Phone.pure()),
      ];

      final inputsC = <
          FormInput<dynamic, FormInputValidator<dynamic, ValidationError>,
              dynamic>>[
        FormInput(AuthFormField.email, const Email.pure()),
        FormInput(AuthFormField.password, const Password.pure()),
        FormInput('name', const Name.pure()),
        FormInput('phone', const Phone.pure()),
      ];

      blocTest<SignUpCubit<int>, SignUpState>(
        'emits no state when apply intersection with the same form',
        build: () => SignUpCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignUpState(
          form: WyattFormImpl(
            inputsA,
            name: AuthFormName.signUpForm,
          ),
        ),
        act: (cubit) => cubit.update(
          WyattFormImpl(inputsA, name: 'otherSignUpForm'),
          operation: SetOperation.intersection,
        ),
        expect: () => <SignUpState>[],
      );

      blocTest<SignUpCubit<int>, SignUpState>(
        'emits no state when apply intersection with a form that '
        'contains every inputs of actual form',
        build: () => SignUpCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignUpState(
          form: WyattFormImpl(
            inputsA,
            name: AuthFormName.signUpForm,
          ),
        ),
        act: (cubit) => cubit.update(
          WyattFormImpl(inputsC, name: 'otherSignUpForm'),
          operation: SetOperation.intersection,
        ),
        expect: () => <SignUpState>[],
      );

      blocTest<SignUpCubit<int>, SignUpState>(
        'emits the form intersection when apply '
        'intersection with a smaller form',
        build: () => SignUpCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignUpState(
          form: WyattFormImpl(
            inputsC,
            name: AuthFormName.signUpForm,
          ),
        ),
        act: (cubit) => cubit.update(
          WyattFormImpl(inputsA, name: 'otherSignUpForm'),
          operation: SetOperation.intersection,
        ),
        expect: () => <SignUpState>[
          SignUpState(
            form: WyattFormImpl(
              inputsA,
              name: AuthFormName.signUpForm,
            ),
          ),
        ],
      );

      blocTest<SignUpCubit<int>, SignUpState>(
        'emits no state when apply union with the same form',
        build: () => SignUpCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignUpState(
          form: WyattFormImpl(
            inputsA,
            name: AuthFormName.signUpForm,
          ),
        ),
        act: (cubit) => cubit.update(
          WyattFormImpl(inputsA, name: 'otherSignUpForm'),
          operation: SetOperation.union,
        ),
        expect: () => <SignUpState>[],
      );

      blocTest<SignUpCubit<int>, SignUpState>(
        'emits the form union when apply '
        'union with an another form',
        build: () => SignUpCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignUpState(
          form: WyattFormImpl(
            inputsA,
            name: AuthFormName.signUpForm,
          ),
        ),
        act: (cubit) => cubit.update(
          WyattFormImpl(inputsB, name: 'otherSignUpForm'),
          operation: SetOperation.union,
        ),
        expect: () => <SignUpState>[
          SignUpState(
            form: WyattFormImpl(
              inputsC,
              name: AuthFormName.signUpForm,
            ),
          ),
        ],
      );

      blocTest<SignUpCubit<int>, SignUpState>(
        'emits no state when apply replace with the same form',
        build: () => SignUpCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignUpState(
          form: WyattFormImpl(
            inputsA,
            name: AuthFormName.signUpForm,
          ),
        ),
        act: (cubit) => cubit.update(
          WyattFormImpl(inputsA, name: AuthFormName.signUpForm),
        ),
        expect: () => <SignUpState>[],
      );

      blocTest<SignUpCubit<int>, SignUpState>(
        'emits a state with a new form after the replacement',
        build: () => SignUpCubit(
          authenticationRepository: authenticationRepository,
        ),
        seed: () => SignUpState(
          form: WyattFormImpl(
            inputsA,
            name: AuthFormName.signUpForm,
          ),
        ),
        act: (cubit) => cubit.update(
          WyattFormImpl(inputsC, name: AuthFormName.signUpForm),
        ),
        expect: () => <SignUpState>[
          SignUpState(
            form: WyattFormImpl(
              inputsC,
              name: AuthFormName.signUpForm,
            ),
          ),
        ],
      );
    });
  });
}
