// 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 password
///
/// Gives access to the `updatePassword` method and
/// `onPasswordUpdated` callback.
mixin UpdatePassword<Data> on BaseEditAccountCubit<Data> {
  /// This callback is triggered when a user edits his password.
  FutureOrResult<Data?> onPasswordUpdated(
    Result<Account, AppException> result,
    WyattForm form,
  );

  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 [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 update_password}
  FutureOr<void> updatePassword() async {
    if (state.status.isSubmissionInProgress) {
      return;
    }

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

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

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

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

    return CustomRoutine<Account, Data?>(
      routine: () => authenticationRepository.updatePassword(
        password: password!,
      ),
      attachedLogic: (routineResult) => onPasswordUpdated(
        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();
  }
}
