/// Model de données Conversation avec sérialisation JSON
library conversation_model;

import 'package:json_annotation/json_annotation.dart';
import '../../domain/entities/conversation.dart';
import '../../domain/entities/message.dart';
import 'message_model.dart';

part 'conversation_model.g.dart';

@JsonSerializable(explicitToJson: true)
class ConversationModel extends Conversation {
  @JsonKey(
    fromJson: _messageFromJson,
    toJson: _messageToJson,
  )
  @override
  final Message? lastMessage;

  const ConversationModel({
    required super.id,
    required super.name,
    super.description,
    required super.type,
    required super.participantIds,
    super.organizationId,
    this.lastMessage,
    super.unreadCount,
    super.isMuted,
    super.isPinned,
    super.isArchived,
    required super.createdAt,
    super.updatedAt,
    super.avatarUrl,
    super.metadata,
  }) : super(lastMessage: lastMessage);

  static Message? _messageFromJson(Map<String, dynamic>? json) =>
      json == null ? null : MessageModel.fromJson(json);

  static Map<String, dynamic>? _messageToJson(Message? message) =>
      message == null ? null : MessageModel.fromEntity(message).toJson();

  factory ConversationModel.fromJson(Map<String, dynamic> json) =>
      _$ConversationModelFromJson(json);

  Map<String, dynamic> toJson() => _$ConversationModelToJson(this);

  factory ConversationModel.fromEntity(Conversation conversation) {
    return ConversationModel(
      id: conversation.id,
      name: conversation.name,
      description: conversation.description,
      type: conversation.type,
      participantIds: conversation.participantIds,
      organizationId: conversation.organizationId,
      lastMessage: conversation.lastMessage,
      unreadCount: conversation.unreadCount,
      isMuted: conversation.isMuted,
      isPinned: conversation.isPinned,
      isArchived: conversation.isArchived,
      createdAt: conversation.createdAt,
      updatedAt: conversation.updatedAt,
      avatarUrl: conversation.avatarUrl,
      metadata: conversation.metadata,
    );
  }

  Conversation toEntity() => this;
}
