import 'dart:convert';

/// A harvester's ground-truth correction for a [PalmRecord]'s AI inference.
/// Additive/append-only: a new correction is a new row, never an edit to
/// the AI's original record or to a prior correction.
class PalmCorrection {
  final int? id;
  final int originalRecordId;
  final String correctedClass;
  final List<Map<String, dynamic>> correctedDetections;
  final DateTime timestamp;

  PalmCorrection({
    this.id,
    required this.originalRecordId,
    required this.correctedClass,
    required this.correctedDetections,
    required this.timestamp,
  });

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'original_record_id': originalRecordId,
      'corrected_class': correctedClass,
      'corrected_detections': json.encode(correctedDetections),
      'timestamp': timestamp.toIso8601String(),
    };
  }

  factory PalmCorrection.fromMap(Map<String, dynamic> map) {
    return PalmCorrection(
      id: map['id'],
      originalRecordId: map['original_record_id'],
      correctedClass: map['corrected_class'],
      correctedDetections: map['corrected_detections'] != null
          ? List<Map<String, dynamic>>.from(json.decode(map['corrected_detections']))
          : [],
      timestamp: DateTime.parse(map['timestamp']),
    );
  }

  String toJson() => json.encode(toMap());

  factory PalmCorrection.fromJson(String source) => PalmCorrection.fromMap(json.decode(source));
}
