import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:em2rp/models/vehicle_model.dart';

class VehicleService {
  final FirebaseFirestore _db = FirebaseFirestore.instance;
  static const String _collection = 'vehicles';

  /// Récupère tous les véhicules, triés par nom.
  Future<List<VehicleModel>> getVehicles() async {
    final snapshot = await _db
        .collection(_collection)
        .orderBy('name')
        .get();
    return snapshot.docs
        .map((doc) => VehicleModel.fromFirestore(doc))
        .toList();
  }

  /// Stream en temps réel
  Stream<List<VehicleModel>> watchVehicles() {
    return _db
        .collection(_collection)
        .orderBy('name')
        .snapshots()
        .map((snap) =>
            snap.docs.map((d) => VehicleModel.fromFirestore(d)).toList());
  }

  /// Ajoute un véhicule
  Future<String> addVehicle(VehicleModel vehicle) async {
    final ref = await _db.collection(_collection).add(vehicle.toMap());
    return ref.id;
  }

  /// Modifie un véhicule existant
  Future<void> updateVehicle(VehicleModel vehicle) async {
    final map = vehicle.toMap();
    map.remove('createdAt'); // Ne pas écraser la date de création
    await _db.collection(_collection).doc(vehicle.id).update(map);
  }

  /// Supprime un véhicule
  Future<void> deleteVehicle(String vehicleId) async {
    await _db.collection(_collection).doc(vehicleId).delete();
  }
}
