// Copyright (C) 2023 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 'dart:async';

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

/// Sign up mixin.
///
/// Allows the user to register with an email and a password.
///
/// Gives access to the `signUpWithEmailPassword` method and
/// `onSignUpWithEmailAndPassword` callback.
mixin SignUpWithEmailPassword<Data> on BaseSignUpCubit<Data> {
  /// This callback is triggered when a user creates an account.
  ///
  /// For example: when a user sign up in firebase.
  FutureOrResult<Data?> onSignUpWithEmailAndPassword(
    Result<Account, AppException> result,
    WyattForm form,
  );

  void emailChanged(String value) {
    final emailValidatorType = formRepository
        .accessForm(formName)
        .validatorOf(AuthFormField.email)
        .runtimeType;
    assert(
      emailValidatorType == Email,
      'Use emailCustomChanged(...) with validator $emailValidatorType',
    );

    final Email email = Email.dirty(value);
    dataChanged(AuthFormField.email, email);
  }

  void passwordChanged(String value) {
    final passwordValidatorType = formRepository
        .accessForm(formName)
        .validatorOf(AuthFormField.password)
        .runtimeType;
    assert(
      passwordValidatorType == Password,
      'Use passwordCustomChanged(...) with validator $passwordValidatorType',
    );
    final Password password = Password.dirty(value);
    dataChanged(AuthFormField.password, password);
  }

  /// Same as [emailChanged] but with a custom [Validator].
  ///
  /// Sort of short hand for [dataChanged].
  void emailCustomChanged<
      Validator extends FormInputValidator<String?, ValidationError>>(
    Validator validator,
  ) {
    dataChanged(AuthFormField.email, validator);
  }

  /// Same as [passwordChanged] but with a custom [Validator].
  ///
  /// Sort of short hand for [dataChanged].
  void passwordCustomChanged<
      Validator extends FormInputValidator<String?, ValidationError>>(
    Validator validator,
  ) {
    dataChanged(AuthFormField.password, validator);
  }

  /// {@macro signup_pwd}
  FutureOr<void> signUpWithEmailPassword() async {
    if (!state.status.isValidated) {
      return;
    }

    final form = formRepository.accessForm(formName);
    emit(SignUpState(form: form, status: FormStatus.submissionInProgress));

    final email = form.valueOf<String?>(AuthFormField.email);
    final password = form.valueOf<String?>(AuthFormField.password);

    if (email.isNullOrEmpty || password.isNullOrEmpty) {
      emit(
        SignUpState(
          form: form,
          errorMessage: 'An error occured while retrieving data from the form.',
          status: FormStatus.submissionFailure,
        ),
      );
    }

    return CustomRoutine<Account, Data?>(
      routine: () => authenticationRepository.signUpWithEmailAndPassword(
        email: email!,
        password: password!,
      ),
      attachedLogic: (routineResult) => onSignUpWithEmailAndPassword(
        routineResult,
        form,
      ),
      onError: (error) {
        emit(
          SignUpState(
            form: form,
            errorMessage: error.message,
            status: FormStatus.submissionFailure,
          ),
        );
        addError(error);
      },
      onSuccess: (account, data) {
        authenticationRepository.addSession(
          AuthenticationSession.fromEvent(
            SignedUpEvent(account: account),
            data: data,
          ),
        );
        emit(
          SignUpState(
            form: form,
            status: FormStatus.submissionSuccess,
          ),
        );
      },
    ).call();
  }
}
