import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:remever/common/functions.dart';
import 'package:remever/inject.dart';
import 'package:remever/router.gr.dart';
import 'package:remever/services/auth/auth_interface.dart';

part 'auth_state.dart';
part 'auth_cubit.freezed.dart';

class AuthCubit extends Cubit<AuthState> {
  AuthCubit() : super(AuthState.initial());

  final AuthInterface _authInterface = getIt<AuthInterface>();

  Future<void> toInitialState() async {
    emit(AuthState.initial());
  }

  Future<void> toEmailState() async {
    emit(AuthState.email());
  }

  Future<void> toCodeState(String email, String uuid) async {
    emit(AuthState.code(email, uuid));
  }

  /// Авторизация
  Future<void> login(String email) async {
    final String? uuid = await _authInterface.login(email);

    if (uuid == null) {
      return;
    }

    toCodeState(email, uuid);
  }

  Future<void> sendCode(String code, String uid) async {
    final bool res = await _authInterface.sendCode(code, uid);

    if (!res) {
      toInitialState();
      return;
    }

    globalRouter.replace(CollectionRoute());
  }
}
