import 'dart:convert';

import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:moneymgr_mobile/services/api/auth_api.dart';
import 'package:moneymgr_mobile/services/api/server_api.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared_preferences/shared_preferences.dart';

part 'prefs.g.dart';

@riverpod
Future<SharedPreferencesWithCache> prefs(Ref ref) =>
    SharedPreferencesWithCache.create(
      cacheOptions: const SharedPreferencesWithCacheOptions(),
    );

extension MoneyMgrSharedPreferences on SharedPreferencesWithCache {
  bool startOnScansListScreen() {
    return getBool("startOnScansListScreen") ?? false;
  }

  Future<void> setStartOnScansListScreen(bool start) async {
    await setBool("startOnScansListScreen", start);
  }

  bool disableExtractDates() {
    return getBool("disableExtractDates") ?? false;
  }

  Future<void> setDisableExtractDates(bool disable) async {
    await setBool("disableExtractDates", disable);
  }

  ServerConfig? serverConfig() {
    final json = getString("serverConfig");
    if (json != null) return ServerConfig.fromJson(jsonDecode(json));
    return null;
  }

  Future<void> setServerConfig(ServerConfig config) async {
    await setString("serverConfig", jsonEncode(config));
  }

  Future<void> clearServerConfig() async {
    await remove("serverConfig");
  }

  AuthInfo? authInfo() {
    final json = getString("authInfo");
    if (json != null) return AuthInfo.fromJson(jsonDecode(json));
    return null;
  }

  Future<void> setAuthInfo(AuthInfo info) async {
    await setString("authInfo", jsonEncode(info));
  }

  Future<void> clearAuthInfo() async {
    await remove("authInfo");
  }
}
