import 'package:hive/hive.dart';

part 'operation_model.g.dart';

@HiveType(typeId: 1)
class OperationModel extends HiveObject {
  @HiveField(0)
  final int id;

  @HiveField(1)
  final String name;

  @HiveField(2)
  final DateTime dateDebut;

  @HiveField(3)
  final DateTime dateFin;

  @HiveField(4)
  DateTime lastSyncedAt;

  @HiveField(5)
  bool isActive;

  @HiveField(6)
  bool isSynced;

  OperationModel({
    required this.id,
    required this.name,
    required this.dateDebut,
    required this.dateFin,
    required this.lastSyncedAt,
    this.isActive = true,
    this.isSynced = false,
  });

  // Factory pour convertir depuis JSON (API)
  factory OperationModel.fromJson(Map<String, dynamic> json) {
    // Convertir l'ID en int, qu'il soit déjà int ou string
    final dynamic rawId = json['id'];
    final int id = rawId is String ? int.parse(rawId) : rawId as int;
    
    return OperationModel(
      id: id,
      name: json['name'],
      dateDebut: DateTime.parse(json['date_deb']),
      dateFin: DateTime.parse(json['date_fin']),
      lastSyncedAt: DateTime.now(),
      isActive: true,
      isSynced: true,
    );
  }

  // Convertir en JSON pour l'API
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'date_deb': dateDebut.toIso8601String().split('T')[0], // Format YYYY-MM-DD
      'date_fin': dateFin.toIso8601String().split('T')[0], // Format YYYY-MM-DD
      'is_active': isActive,
    };
  }

  // Copier avec de nouvelles valeurs
  OperationModel copyWith({
    String? name,
    DateTime? dateDebut,
    DateTime? dateFin,
    bool? isActive,
    bool? isSynced,
    DateTime? lastSyncedAt,
  }) {
    return OperationModel(
      id: this.id,
      name: name ?? this.name,
      dateDebut: dateDebut ?? this.dateDebut,
      dateFin: dateFin ?? this.dateFin,
      lastSyncedAt: lastSyncedAt ?? this.lastSyncedAt,
      isActive: isActive ?? this.isActive,
      isSynced: isSynced ?? this.isSynced,
    );
  }
}
