import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

class AppStorage {
  AppStorage._();

  static SharedPreferences? _prefs;

  static Future<void> init() async {
    _prefs ??= await SharedPreferences.getInstance();
  }

  static SharedPreferences get instance {
    final prefs = _prefs;
    if (prefs == null) {
      throw StateError('AppStorage.init() must be called before use.');
    }
    return prefs;
  }

  static String? getString(String key) => instance.getString(key);

  static Future<bool> setString(String key, String value) {
    return instance.setString(key, value);
  }

  static int getInt(String key, {int defaultValue = 0}) {
    return instance.getInt(key) ?? defaultValue;
  }

  static Future<bool> setInt(String key, int value) {
    return instance.setInt(key, value);
  }

  static bool getBool(String key, {bool defaultValue = false}) {
    return instance.getBool(key) ?? defaultValue;
  }

  static Future<bool> setBool(String key, bool value) {
    return instance.setBool(key, value);
  }

  static List<String> getStringList(String key) {
    return instance.getStringList(key) ?? const [];
  }

  static Future<bool> setStringList(String key, List<String> value) {
    return instance.setStringList(key, value);
  }

  static Map<String, dynamic>? getJson(String key) {
    final raw = instance.getString(key);
    if (raw == null || raw.isEmpty) return null;
    final decoded = jsonDecode(raw);
    return decoded is Map<String, dynamic> ? decoded : null;
  }

  static Future<bool> setJson(String key, Map<String, dynamic> value) {
    return instance.setString(key, jsonEncode(value));
  }

  static bool containsKey(String key) => instance.containsKey(key);

  static Future<bool> remove(String key) => instance.remove(key);

  static Future<bool> clear() => instance.clear();
}
