// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:io';

import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

import 'package:flutter_pos_ecommerce/module/ecommerce/data/datasources/auth_remote_datasource.dart';

part 'profile_bloc.freezed.dart';
part 'profile_event.dart';
part 'profile_state.dart';

class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
  final AuthRemoteDatasource _datasource;
  ProfileBloc(
    this._datasource,
  ) : super(const _Initial()) {
    on<_GetProfile>((event, emit) async {
      emit(const ProfileState.loading());
      final result = await _datasource.getProfile();
      result.fold(
        (failure) => emit(ProfileState.error(message: failure)),
        (profile) => emit(ProfileState.profileLoaded(profile: profile)),
      );
    });

    on<_UpdateProfile>((event, emit) async {
      emit(const ProfileState.loading());
      final result = await _datasource.updateProfile(
        name: event.name,
        email: event.email,
        phone: event.phone,
        foto: event.foto,
      );
      result.fold(
        (failure) => emit(ProfileState.error(message: failure)),
        (_) => emit(const ProfileState.profileUpdated()),
      );
    });
  }
}
