/// Model untuk data sensor IoT (suhu & kelembapan).
class SensorModel {
  final double temperature;
  final double humidity;
  final bool relayOn;
  final String mode;
  final DateTime timestamp;

  const SensorModel({
    required this.temperature,
    required this.humidity,
    this.relayOn = false,
    this.mode = 'auto',
    required this.timestamp,
  });

  factory SensorModel.fromJson(Map<String, dynamic> json) {
    return SensorModel(
      temperature: (json['temperature'] as num?)?.toDouble() ?? 0.0,
      humidity: (json['humidity'] as num?)?.toDouble() ?? 0.0,
      relayOn: json['relay_state'] as bool? ?? false,
      mode: json['mode'] as String? ?? 'auto',
      timestamp: json['timestamp'] != null
          ? DateTime.parse(json['timestamp'] as String)
          : (json['created_at'] != null
              ? DateTime.parse(json['created_at'] as String)
              : DateTime.now()),
    );
  }

  Map<String, dynamic> toJson() => {
    'temperature': temperature,
    'humidity': humidity,
    'relay_state': relayOn,
    'mode': mode,
    'timestamp': timestamp.toIso8601String(),
  };

  SensorModel copyWith({
    double? temperature,
    double? humidity,
    bool? relayOn,
    String? mode,
    DateTime? timestamp,
  }) {
    return SensorModel(
      temperature: temperature ?? this.temperature,
      humidity: humidity ?? this.humidity,
      relayOn: relayOn ?? this.relayOn,
      mode: mode ?? this.mode,
      timestamp: timestamp ?? this.timestamp,
    );
  }

  @override
  String toString() =>
      'SensorModel(temp: $temperature°C, hum: $humidity%, relay: $relayOn, mode: $mode, ts: $timestamp)';
}
