import 'package:hive/hive.dart';

part 'room.g.dart';

/// Modèle simple de conversation/room
@HiveType(typeId: 50)
class Room extends HiveObject {
  @HiveField(0)
  final String id;
  
  @HiveField(1)
  final String title;
  
  @HiveField(2)
  final String type; // 'private' ou 'group'
  
  @HiveField(3)
  final DateTime createdAt;
  
  @HiveField(4)
  final String? lastMessage;
  
  @HiveField(5)
  final DateTime? lastMessageAt;
  
  @HiveField(6)
  final int unreadCount;
  
  @HiveField(7)
  final List<Map<String, dynamic>>? recentMessages;
  
  @HiveField(8)
  final DateTime? updatedAt;
  
  @HiveField(9)
  final int? createdBy;
  
  @HiveField(10)
  final bool isSynced;
  
  Room({
    required this.id,
    required this.title,
    required this.type,
    required this.createdAt,
    this.lastMessage,
    this.lastMessageAt,
    this.unreadCount = 0,
    this.recentMessages,
    this.updatedAt,
    this.createdBy,
    this.isSynced = true,
  });
  
  // Simple factory depuis JSON
  factory Room.fromJson(Map<String, dynamic> json) {
    return Room(
      id: json['id'],
      title: json['title'] ?? 'Sans titre',
      type: json['type'] ?? 'private',
      createdAt: DateTime.parse(json['created_at'] ?? json['date_creation']),
      lastMessage: json['last_message'],
      lastMessageAt: json['last_message_at'] != null 
          ? DateTime.parse(json['last_message_at'])
          : null,
      unreadCount: json['unread_count'] ?? 0,
      recentMessages: json['recent_messages'] != null
          ? List<Map<String, dynamic>>.from(json['recent_messages'])
          : null,
      updatedAt: json['updated_at'] != null
          ? DateTime.parse(json['updated_at'])
          : null,
      createdBy: json['created_by'],
      isSynced: json['is_synced'] ?? true,
    );
  }
  
  // Simple conversion en JSON
  Map<String, dynamic> toJson() => {
    'id': id,
    'title': title,
    'type': type,
    'date_creation': createdAt.toIso8601String(),
  };
  
  // Méthode copyWith pour faciliter les mises à jour
  Room copyWith({
    String? id,
    String? title,
    String? type,
    DateTime? createdAt,
    String? lastMessage,
    DateTime? lastMessageAt,
    int? unreadCount,
    List<Map<String, dynamic>>? recentMessages,
    DateTime? updatedAt,
    int? createdBy,
    bool? isSynced,
  }) {
    return Room(
      id: id ?? this.id,
      title: title ?? this.title,
      type: type ?? this.type,
      createdAt: createdAt ?? this.createdAt,
      lastMessage: lastMessage ?? this.lastMessage,
      lastMessageAt: lastMessageAt ?? this.lastMessageAt,
      unreadCount: unreadCount ?? this.unreadCount,
      recentMessages: recentMessages ?? this.recentMessages,
      updatedAt: updatedAt ?? this.updatedAt,
      createdBy: createdBy ?? this.createdBy,
      isSynced: isSynced ?? this.isSynced,
    );
  }
}