// 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/utils/custom_routine.dart';
import 'package:wyatt_authentication_bloc/src/domain/entities/entities.dart';
import 'package:wyatt_authentication_bloc/src/features/sign_in/cubit/sign_in_cubit.dart';
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';

/// Sign in mixin.
///
/// Allows the user to sign in anonymously
///
/// Gives access to the `signInAnonymously` method and
/// `onSignInAnonymously` callback.
mixin SignInAnonymously<Data> on BaseSignInCubit<Data> {
  /// This callback is triggered when a user signs in anonymously.
  FutureOrResult<Data?> onSignInAnonymously(
    Result<Account, AppException> result,
    WyattForm form,
  );

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

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

    return CustomRoutine<Account, Data?>(
      routine: authenticationRepository.signInAnonymously,
      attachedLogic: (routineResult) => onSignInAnonymously(
        routineResult,
        form,
      ),
      onError: (error) {
        emit(
          SignInState(
            form: form,
            errorMessage: error.message,
            status: FormStatus.submissionFailure,
          ),
        );
        addError(error);
      },
      onSuccess: (account, data) {
        authenticationRepository.addSession(
          AuthenticationSession.fromEvent(
            SignedInEvent(account: account),
            data: data,
          ),
        );
        emit(
          SignInState(
            form: form,
            status: FormStatus.submissionSuccess,
          ),
        );
      },
    ).call();
  }
}
