import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';

import '../../networking/restful_api_viewmodel.dart';
import '../../permission/biometric_manager.dart';
import '../../preference/data_preference.dart';

class SettingViewModel extends RestfulApiViewModel {
  bool biometricEnabled = false;

  Future<bool> loadBiometricStatus() async {
    final phone = DataPreference.instance.phone;
    if (phone != null) {
      final token = await DataPreference.instance.getBioToken(phone) ?? "";
      biometricEnabled = token.isNotEmpty;
    } else {
      biometricEnabled = false;
    }
    return biometricEnabled;
  }

  Future<bool> toggleBiometric(bool enable) async {
    final phone = DataPreference.instance.phone;
    if (phone == null) return biometricEnabled;
    try {
      final supported = await BiometricManager().isDeviceSupported();
      if (!supported) return biometricEnabled;
      final canCheck = await BiometricManager().canCheckBiometrics();
      if (!canCheck) return biometricEnabled;
      final didAuth = await BiometricManager().authenticateBiometric();
      if (!didAuth) return biometricEnabled;
      showLoading();
      if (enable) {
        final value = await client.registerBiometric();
        final token = value.data?.bioToken ?? "";
        await DataPreference.instance.saveBioToken(token);
        return true;
      } else {
        await client.unRegisterBiometric();
        await DataPreference.instance.clearBioToken(phone);
        return false;
      }
    } catch (_) {
      return biometricEnabled;
    } finally {
      hideLoading();
    }
  }
}
