import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

/// 本地草稿持久化服务，通过 MethodChannel 调用原生 SharedPreferences / NSUserDefaults。
///
/// 避免引入 shared_preferences 包，不需要 Kotlin 插件。
class DraftStorage {
  static const _channel = MethodChannel('com.tboss.oa/storage');
  static const _prefix = 'oa_draft_';

  /// 保存草稿
  static Future<void> save(String key, Map<String, dynamic> data) async {
    final fullKey = _prefix + key;
    try {
      await _channel.invokeMethod('setString', {
        'key': fullKey,
        'value': jsonEncode(data),
      });
      debugPrint('[DraftStorage] save($fullKey) success');
    } catch (e) {
      debugPrint('[DraftStorage] save($fullKey) error: $e');
    }
  }

  /// 读取草稿，不存在返回 null
  static Future<Map<String, dynamic>?> load(String key) async {
    final fullKey = _prefix + key;
    try {
      final raw = await _channel.invokeMethod<String>('getString', {
        'key': fullKey,
      });
      debugPrint('[DraftStorage] load($fullKey) = ${raw != null ? 'found (${raw.length} chars)' : 'null'}');
      if (raw == null || raw.isEmpty) return null;
      return jsonDecode(raw) as Map<String, dynamic>;
    } catch (e) {
      debugPrint('[DraftStorage] load($fullKey) error: $e');
      return null;
    }
  }

  /// 是否有草稿
  static Future<bool> has(String key) async {
    try {
      final fullKey = _prefix + key;
      final result = await _channel.invokeMethod('hasKey', {
        'key': fullKey,
      });
      // iOS 端 @(YES) 在某些 Flutter 版本被编解码为 int(0/1) 而非 bool
      final exists = result == true || result == 1;
      debugPrint('[DraftStorage] has($fullKey) = $exists (raw: $result, type: ${result.runtimeType})');
      return exists;
    } catch (e) {
      debugPrint('[DraftStorage] has($key) error: $e');
      return false;
    }
  }

  /// 删除草稿
  static Future<void> delete(String key) async {
    await _channel.invokeMethod('remove', {'key': _prefix + key});
  }
}
