import 'package:mypoint_flutter_app/core/network/restful_api_client_all_request.dart';
import '../../core/network/restful_api_viewmodel.dart';
import '../../core/services/biometric_manager.dart';
import '../../shared/preferences/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();
    }
  }
}
