import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/chat_message_model.dart';

/// Local datasource for caching chat messages using SharedPreferences.
class ChatLocalDatasource {
  final SharedPreferences _prefs;

  static const String _cacheKeyPrefix = 'chat_messages_';

  ChatLocalDatasource(this._prefs);

  /// Caches messages for a given session.
  Future<void> cacheMessages(
    String sessionId,
    List<ChatMessageModel> messages,
  ) async {
    final key = '$_cacheKeyPrefix$sessionId';
    final jsonList = messages.map((m) => m.toJson()).toList();
    await _prefs.setString(key, jsonEncode(jsonList));
  }

  /// Retrieves cached messages for a given session.
  /// Returns an empty list if no cache exists.
  List<ChatMessageModel> getCachedMessages(String sessionId) {
    final key = '$_cacheKeyPrefix$sessionId';
    final cached = _prefs.getString(key);
    if (cached == null) return [];

    try {
      final jsonList = jsonDecode(cached) as List;
      return jsonList
          .map((m) => ChatMessageModel.fromJson(m as Map<String, dynamic>))
          .toList();
    } catch (_) {
      return [];
    }
  }

  /// Clears the cached messages for a given session.
  Future<void> clearCache(String sessionId) async {
    final key = '$_cacheKeyPrefix$sessionId';
    await _prefs.remove(key);
  }

  /// Clears all cached chat sessions.
  Future<void> clearAllCaches() async {
    final keys = _prefs.getKeys().where((k) => k.startsWith(_cacheKeyPrefix));
    for (final key in keys) {
      await _prefs.remove(key);
    }
  }
}
