import 'package:cloud_firestore/cloud_firestore.dart'; import '../models/trip.dart'; import '../services/error_service.dart'; class TripRepository { final FirebaseFirestore _firestore = FirebaseFirestore.instance; final _errorService = ErrorService(); CollectionReference get _tripsCollection => _firestore.collection('trips'); // Récupérer tous les voyages d'un utilisateur Stream> getTripsByUserId(String userId) { try { return _tripsCollection .where('participants', arrayContains: userId) .snapshots() .map((snapshot) { final trips = snapshot.docs .map((doc) { try { final data = doc.data() as Map; return Trip.fromMap(data, doc.id); } catch (e, stackTrace) { _errorService.logError( 'TripRepository', 'Erreur parsing trip ${doc.id}: $e', stackTrace, ); return null; } }) .whereType() .toList(); return trips; }); } catch (e, stackTrace) { _errorService.logError( 'TripRepository', 'Erreur stream trips: $e', stackTrace, ); throw Exception('Impossible de récupérer les voyages'); } } // Créer un voyage et retourner son ID Future createTrip(Trip trip) async { try { final tripData = trip.toMap(); // Ne pas modifier les timestamps ici, ils sont déjà au bon format final docRef = await _tripsCollection.add(tripData); return docRef.id; } catch (e, stackTrace) { _errorService.logError( 'TripRepository', 'Erreur création trip: $e', stackTrace, ); throw Exception('Impossible de créer le voyage'); } } // Récupérer un voyage par son ID Future getTripById(String tripId) async { try { final doc = await _tripsCollection.doc(tripId).get(); if (!doc.exists) { return null; } return Trip.fromMap(doc.data() as Map, doc.id); } catch (e, stackTrace) { _errorService.logError( 'TripRepository', 'Erreur get trip: $e', stackTrace, ); throw Exception('Impossible de récupérer le voyage'); } } // Mettre à jour un voyage Future updateTrip(String tripId, Trip trip) async { try { final tripData = trip.toMap(); // Mettre à jour le timestamp de modification tripData['updatedAt'] = Timestamp.now(); await _tripsCollection.doc(tripId).update(tripData); } catch (e, stackTrace) { _errorService.logError( 'TripRepository', 'Erreur update trip: $e', stackTrace, ); throw Exception('Impossible de mettre à jour le voyage'); } } // Supprimer un voyage Future deleteTrip(String tripId) async { try { await _tripsCollection.doc(tripId).delete(); } catch (e, stackTrace) { _errorService.logError( 'TripRepository', 'Erreur delete trip: $e', stackTrace, ); throw Exception('Impossible de supprimer le voyage'); } } }