import 'package:cloud_firestore/cloud_firestore.dart'; class VehicleModel { final String id; final String name; final double consumptionPer100km; // L/100km (ou kWh/100km si électrique) final String fuelType; // 'Diesel', 'Essence', 'Electrique' final double maintenanceCostPerKm; // €/km final int tollCategoryId; // 1 à 5 (catégorie Ulys) final DateTime? createdAt; const VehicleModel({ required this.id, required this.name, required this.consumptionPer100km, required this.fuelType, required this.maintenanceCostPerKm, required this.tollCategoryId, this.createdAt, }); factory VehicleModel.fromMap(Map map, String id) { return VehicleModel( id: id, name: (map['name'] ?? '').toString(), consumptionPer100km: _parseDouble(map['consumptionPer100km'] ?? 0), fuelType: (map['fuelType'] ?? 'Diesel').toString(), maintenanceCostPerKm: _parseDouble(map['maintenanceCostPerKm'] ?? 0), tollCategoryId: _parseInt(map['tollCategoryId'] ?? 2), createdAt: map['createdAt'] is Timestamp ? (map['createdAt'] as Timestamp).toDate() : null, ); } factory VehicleModel.fromFirestore(DocumentSnapshot doc) { return VehicleModel.fromMap( doc.data() as Map, doc.id, ); } Map toMap() { return { 'name': name, 'consumptionPer100km': consumptionPer100km, 'fuelType': fuelType, 'maintenanceCostPerKm': maintenanceCostPerKm, 'tollCategoryId': tollCategoryId, 'createdAt': createdAt != null ? Timestamp.fromDate(createdAt!) : FieldValue.serverTimestamp(), }; } VehicleModel copyWith({ String? id, String? name, double? consumptionPer100km, String? fuelType, double? maintenanceCostPerKm, int? tollCategoryId, }) { return VehicleModel( id: id ?? this.id, name: name ?? this.name, consumptionPer100km: consumptionPer100km ?? this.consumptionPer100km, fuelType: fuelType ?? this.fuelType, maintenanceCostPerKm: maintenanceCostPerKm ?? this.maintenanceCostPerKm, tollCategoryId: tollCategoryId ?? this.tollCategoryId, createdAt: createdAt, ); } /// Label lisible pour l'unité de consommation String get consumptionUnit { if (fuelType == 'Electrique') return 'kWh/100km'; return 'L/100km'; } static double _parseDouble(dynamic v) { if (v is double) return v; if (v is int) return v.toDouble(); if (v is String) return double.tryParse(v) ?? 0.0; return 0.0; } static int _parseInt(dynamic v) { if (v is int) return v; if (v is double) return v.toInt(); if (v is String) return int.tryParse(v) ?? 2; return 2; } }