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;

  @HiveField(7)
  final int fkEntite;

  OperationModel({
    required this.id,
    required this.name,
    required this.dateDebut,
    required this.dateFin,
    required this.lastSyncedAt,
    required this.fkEntite,
    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;
    final dynamic rawEntite = json['fk_entite'];
    final int fkEntite = rawEntite is String ? int.parse(rawEntite) : rawEntite as int;

    return OperationModel(
      id: id,
      name: json['libelle'], // ← Correction: utiliser 'libelle' au lieu de 'name'
      dateDebut: DateTime.parse(json['date_deb']),
      dateFin: DateTime.parse(json['date_fin']),
      lastSyncedAt: DateTime.now(),
      isActive: json['chk_active'] == true || json['chk_active'] == 1 || json['chk_active'] == "1",
      isSynced: true,
      fkEntite: fkEntite,
    );
  }

  // 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,
      'fk_entite': fkEntite,
    };
  }

  // Copier avec de nouvelles valeurs
  OperationModel copyWith({
    String? name,
    DateTime? dateDebut,
    DateTime? dateFin,
    bool? isActive,
    bool? isSynced,
    DateTime? lastSyncedAt,
    int? fkEntite,
  }) {
    return OperationModel(
      id: 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,
      fkEntite: fkEntite ?? this.fkEntite,
    );
  }
}
