import 'package:rasadyar_core/core.dart';
import 'package:rasadyar_inspection/data/model/response/user_profile/user_profile_model.dart';
import 'package:rasadyar_inspection/data/repositories/user/user_repository_imp.dart';
import 'package:rasadyar_inspection/injection/inspection_di.dart';
import 'package:rasadyar_inspection/inspection.dart';

class ProfileLogic extends GetxController {
  RootLogic rootLogic = Get.find<RootLogic>();
  UserRepositoryImp userRepository = diInspection.get<UserRepositoryImp>();
  Rx<Resource<UserProfileModel>> userProfile = Resource<UserProfileModel>.loading().obs;

  RxInt selectedRole = 0.obs;
  RxInt selectedInformationType = 0.obs;

  @override
  void onReady() {
    super.onReady();
    rootLogic.userProfile.listen((data) {
      if (data != null) {
        userProfile.value = Resource<UserProfileModel>.success(data);
      } else {
        userProfile.value = Resource<UserProfileModel>.error('Failed to load user profile');
      }
    });
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  Future<void> fetchUserProfile() async {
    userProfile.value = Resource<UserProfileModel>.loading();

    await safeCall(
      call: () => userRepository.fetchUserProfile(
        token: rootLogic.tokenStorageService.accessToken.value ?? '',
      ),
      onSuccess: (profile) {
        if (profile != null) {
          userProfile.value = Resource<UserProfileModel>.success(profile);
        } else {
          userProfile.value = Resource<UserProfileModel>.error('Failed to load user profile');
        }
      },
      onError: (error, stackTrace) {
        userProfile.value = Resource<UserProfileModel>.error(
          'Failed to load user profile: ${error.toString()}',
        );
      },
    );
  }
}
