import 'package:isar/isar.dart';
import '../../domain/entities/chat.dart';
import '../../domain/entities/user.dart';
import '../../domain/entities/message.dart';
import 'message_model.dart';

part 'chat_model.g.dart';

@collection
class ChatModel {
  Id isarId = Isar.autoIncrement;

  @Index(unique: true, replace: true)
  late String id;
  
  late String type;
  late String title;
  String? avatarUrl;
  
  late List<UserModel> participants;
  
  LastMessageModel? lastMessage;
  
  DateTime? lastMessageTime;
  
  int unreadCount = 0;
  bool isMuted = false;
  bool isPinned = false;

  Chat toEntity() {
    return Chat(
      id: id,
      type: type,
      title: title,
      avatarUrl: avatarUrl,
      participants: participants.map((u) => u.toEntity()).toList(),
      lastMessage: lastMessage?.toEntity(),
      lastMessageTime: lastMessageTime,
      unreadCount: unreadCount,
      isMuted: isMuted,
      isPinned: isPinned,
    );
  }

  static ChatModel fromEntity(Chat chat) {
    return ChatModel()
      ..id = chat.id
      ..type = chat.type
      ..title = chat.title
      ..avatarUrl = chat.avatarUrl
      ..participants = chat.participants?.map((u) => UserModel.fromEntity(u)).toList() ?? []
      ..lastMessage = chat.lastMessage != null ? LastMessageModel.fromEntity(chat.lastMessage!) : null
      ..lastMessageTime = chat.lastMessageTime
      ..unreadCount = chat.unreadCount
      ..isMuted = chat.isMuted
      ..isPinned = chat.isPinned;
  }
}

@embedded
class LastMessageModel {
  late String id;
  late String content;
  late String messageType;
  late int sequenceId;
  DateTime? createdAt;
  
  @Enumerated(EnumType.name)
  MessageStatus status = MessageStatus.delivered;

  Message toEntity() {
    return Message(
      id: id,
      chatId: '', // Не критично для превью в списке чатов
      senderId: '',
      content: content,
      messageType: messageType,
      sequenceId: sequenceId,
      createdAt: createdAt,
      status: status,
    );
  }

  static LastMessageModel fromEntity(Message message) {
    return LastMessageModel()
      ..id = message.id
      ..content = message.content
      ..messageType = message.messageType
      ..sequenceId = message.sequenceId
      ..createdAt = message.createdAt
      ..status = message.status;
  }
}

@embedded
class UserModel {
  late String id;
  late String name;
  String? avatarUrl;
  String? role;
  DateTime? lastSeen;
  bool? isOnline;

  User toEntity() {
    return User(
      id: id,
      name: name,
      avatarUrl: avatarUrl,
      role: role,
      lastSeen: lastSeen,
      isOnline: isOnline,
    );
  }

  static UserModel fromEntity(User user) {
    return UserModel()
      ..id = user.id
      ..name = user.name
      ..avatarUrl = user.avatarUrl
      ..role = user.role
      ..lastSeen = user.lastSeen
      ..isOnline = user.isOnline;
  }
}
