import 'package:shared_preferences/shared_preferences.dart'; import 'package:travel_mate/models/trip_document.dart'; /// Service that persists per-trip documents metadata locally. /// /// Documents are stored as JSON in `SharedPreferences` to keep the UI /// responsive offline. Each trip key is `trip_docs_`. The service is /// tolerant to corrupted payloads and resets gracefully to an empty list. class TripDocumentService { /// Loads documents for the given [tripId]. Returns an empty list when none. Future> loadDocuments(String tripId) async { final prefs = await SharedPreferences.getInstance(); final raw = prefs.getString(_key(tripId)); if (raw == null) return const []; try { return TripDocument.decodeList(raw); } catch (_) { await prefs.remove(_key(tripId)); return const []; } } /// Saves the full document list for [tripId]. Future saveDocuments(String tripId, List docs) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString(_key(tripId), TripDocument.encodeList(docs)); } /// Adds a new document entry and persists the updated list. Future> addDocument( String tripId, TripDocument doc, ) async { final current = await loadDocuments(tripId); final updated = [...current, doc]; await saveDocuments(tripId, updated); return updated; } /// Deletes a document by [docId] and persists the change. Future> deleteDocument(String tripId, String docId) async { final current = await loadDocuments(tripId); final updated = current.where((d) => d.id != docId).toList(); await saveDocuments(tripId, updated); return updated; } String _key(String tripId) => 'trip_docs_$tripId'; }