// 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/src/core/constants/form_field.dart';
import 'package:wyatt_authentication_bloc/src/core/utils/custom_routine.dart';
import 'package:wyatt_authentication_bloc/src/domain/domain.dart';
import 'package:wyatt_authentication_bloc/src/features/edit_account/cubit/edit_account_cubit.dart';
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';

/// Edit account mixin.
///
/// Allows the user to edit his email
///
/// Gives access to the `updateEmail` method and
/// `onEmailUpdated` callback.
mixin UpdateEmail<Data> on BaseEditAccountCubit<Data> {
  /// This callback is triggered when user updates his email
  FutureOrResult<Data?> onEmailUpdated(
    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);
  }

  /// 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);
  }

  /// {@macro update_email}
  FutureOr<void> updateEmail() async {
    if (state.status.isSubmissionInProgress) {
      return;
    }

    if (!state.status.isValidated) {
      return;
    }

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

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

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

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