import 'package:cloud_firestore/cloud_firestore.dart';

class HistoryModel {
  final String id;
  final String deviceId;
  final double dropPerMinute;
  final DateTime timestamp;

  HistoryModel({
    required this.id,
    required this.deviceId,
    required this.dropPerMinute,
    required this.timestamp,
  });

  factory HistoryModel.fromFirestore(DocumentSnapshot doc) {
    final data = doc.data() as Map<String, dynamic>;
    return HistoryModel(
      id: doc.id,
      deviceId: data['device_id'] ?? '',
      dropPerMinute: (data['drop_per_menit'] ?? 0).toDouble(),
      timestamp: (data['timestamp'] as Timestamp).toDate(),
    );
  }

  Map<String, dynamic> toFirestore() {
    return {
      'device_id': deviceId,
      'drop_per_menit': dropPerMinute,
      'timestamp': Timestamp.fromDate(timestamp),
    };
  }

  factory HistoryModel.fromMap(String id, Map<String, dynamic> data) {
    return HistoryModel(
      id: id,
      deviceId: data['device_id'] ?? '',
      dropPerMinute: (data['drop_per_menit'] ?? 0).toDouble(),
      timestamp: data['timestamp'] is Timestamp
          ? (data['timestamp'] as Timestamp).toDate()
          : DateTime.parse(data['timestamp']),
    );
  }

  HistoryModel copyWith({
    String? id,
    String? deviceId,
    double? dropPerMinute,
    DateTime? timestamp,
  }) {
    return HistoryModel(
      id: id ?? this.id,
      deviceId: deviceId ?? this.deviceId,
      dropPerMinute: dropPerMinute ?? this.dropPerMinute,
      timestamp: timestamp ?? this.timestamp,
    );
  }

  @override
  String toString() {
    return 'HistoryModel(id: $id, deviceId: $deviceId, dropPerMinute: $dropPerMinute, timestamp: $timestamp)';
  }
}