import 'package:get/get.dart';
import 'package:local_auth/local_auth.dart';
import 'package:mypoint_flutter_app/networking/restful_api_request.dart';
import '../../base/restful_api_viewmodel.dart';
import '../../configs/constants.dart';
import '../../preference/data_preference.dart';

class BiometricViewModel extends RestfulApiViewModel {
  final LocalAuthentication _localAuth = LocalAuthentication();
  var biometricType = Rxn<BiometricType>(); // Loại sinh trắc học (Face ID / Touch ID)
  void Function(String message)? onShowAlertError;
  void Function(bool result)? registerBiometricResponse;

  @override
  void onInit() {
    super.onInit();
    checkBiometricType();
  }

  Future<void> checkBiometricType() async {
    try {
      bool canCheckBiometrics = await _localAuth.canCheckBiometrics;
      List<BiometricType> availableBiometrics = await _localAuth.getAvailableBiometrics();
      if (availableBiometrics.contains(BiometricType.face)) {
        biometricType.value = BiometricType.face;
      } else if (availableBiometrics.contains(BiometricType.fingerprint)) {
        biometricType.value = BiometricType.fingerprint;
      }
    } catch (e) {
      print("Lỗi kiểm tra sinh trắc học: $e");
    }
  }

  Future<void> registerBiometric() async {
    showLoading();
    client.accountBioCredential().then((value) async {
      hideLoading();
      if (value.isSuccess && value.data?.bioToken != null) {
        await DataPreference.instance.saveBioToken(value.data!.bioToken!);
        registerBiometricResponse?.call(true);
      } else {
        final mgs = value.errorMessage ?? Constants.commonError;
        onShowAlertError?.call(mgs);
      }
    });
  }
}