import '/core/constants.dart';

class Contact {
  final int id;
  final String username;
  String name;
  String surname;
  final String? lastMessage;
  final String? avatarFileId;
  final String? avatarUrl;
  final DateTime? lastMessageTime;
  final bool isOnline;
  final int unreadCount;
  final String? publicKey;
  final bool isLastMsgDecrypted;

  String? get effectiveAvatarUrl => avatarUrl ?? (avatarFileId != null ? '${AppConstants.baseUrl}/media/$avatarFileId' : null);

  Contact({
    required this.id,
    required this.username,
    required this.name,
    required this.surname,  
    this.lastMessage,
    this.avatarFileId,
    this.avatarUrl,
    this.lastMessageTime,
    this.isOnline = false,
    this.unreadCount = 0,
    this.publicKey,
    this.isLastMsgDecrypted = false,
  });

  Contact copyWith({
    int? id,
    String? username,
    String? name,
    String? surname,
    String? lastMessage,
    String? avatarFileId,
    String? avatarUrl,
    DateTime? lastMessageTime,
    bool? isOnline,
    int? unreadCount,
    String? publicKey,
    bool? isLastMsgDecrypted,
  }) {
    return Contact(
      id: id ?? this.id,
      username: username ?? this.username,
      name: name ?? this.name,
      surname: surname ?? this.surname,
      lastMessage: lastMessage ?? this.lastMessage,
      avatarFileId: avatarFileId ?? this.avatarFileId,
      avatarUrl: avatarUrl ?? this.avatarUrl,
      lastMessageTime: lastMessageTime ?? this.lastMessageTime,
      isOnline: isOnline ?? this.isOnline,
      unreadCount: unreadCount ?? this.unreadCount,
      publicKey: publicKey ?? this.publicKey,
      isLastMsgDecrypted: isLastMsgDecrypted ?? this.isLastMsgDecrypted,
    );
  }

  factory Contact.fromJson(Map<String, dynamic> json) {
    DateTime? parseTime(dynamic value) {
      if (value == null) return null;
      if (value is DateTime) return value;
      final asString = value.toString();
      return DateTime.tryParse(asString);
    }

    return Contact(
      id: json['id'],
      username: json['username'] ?? 'Unknown',
      name: json['name'] ?? json['first_name'] ?? 'Unknown',
      surname: json['surname'] ?? json['last_name'] ?? 'Unknown',
      lastMessage: json['last_message'] ?? json['lastMessage'],
      avatarFileId: json['avatar_file_id'] ?? json['avatarFileId'],
      avatarUrl: json['avatar_url'] ?? json['avatarUrl'],
      lastMessageTime: parseTime(json['last_message_time'] ?? json['lastMessageTime']),
      isOnline: (json['is_online'] ?? json['isOnline']) == true,
      unreadCount: int.tryParse((json['unread_count'] ?? json['unreadCount'] ?? 0).toString()) ?? 0,
      publicKey: json['public_key'],
      isLastMsgDecrypted: json['is_last_msg_decrypted'] ?? false,
    );
  }
}
