import 'package:food_delivery_client/feature/auth/domain/usecases/login_usecase.dart';
import 'package:food_delivery_client/feature/common/presentation/widgets/w_toastification.dart';
import 'package:food_delivery_client/food_delivery_client.dart';

part 'login_event.dart';

part 'login_state.dart';

part 'login_bloc.freezed.dart';

@injectable
class LoginBloc extends Bloc<LoginEvent, LoginState> {
  final LoginUseCase _loginUseCase;
  final StorageService _storageService;

  LoginBloc(this._loginUseCase, this._storageService)
    : super(const LoginState()) {
    on<_Login>(_onLogin);
  }

  Future<void> _onLogin(_Login event, Emitter<LoginState> emit) async {
    emit(state.copyWith(status: RequestStatus.loading));

    final response = await _loginUseCase.call(event.params);

    response.fold(
      (l) {
        log("${l.errorMessage}");
        showErrorToast(l.errorMessage);
        emit(state.copyWith(status: RequestStatus.error));
      },
      (r) {
        showSuccessToast("Login success");
        _storageService.setString(key: AppLocaleKeys.token, value: r.token);
        final token = _storageService.getString(key: AppLocaleKeys.token);
        log('Token:$token');
        emit(state.copyWith(status: RequestStatus.loaded));
      },
    );
  }
}
