/// 聊天室加密金鑰實體
/// 包含會話金鑰和 round 資訊
library;

import 'session_key.dart';

class ChatEncryptionKey {
  final String chatId;           // 聊天室 ID
  final SessionKey sessionKey;   // 當前會話金鑰
  final int activeKeyRound;      // 活躍金鑰的 round 值
  final int currentRound;        // 當前 round
  final bool isSingle;           // 是否為單聊

  const ChatEncryptionKey({
    required this.chatId,
    required this.sessionKey,
    required this.activeKeyRound,
    required this.currentRound,
    required this.isSingle,
  });

  /// 獲取當前活躍的會話金鑰
  SessionKey get activeKey {
    return sessionKey.forRound(activeKeyRound);
  }

  /// 檢查是否需要更新金鑰
  bool get needsKeyRotation => currentRound > activeKeyRound;

  /// 創建隨機聊天室金鑰
  static ChatEncryptionKey generate({
    required String chatId,
    int initialRound = 1,
    bool isSingle = false,
  }) {
    final sessionKey = SessionKey.generate(initialRound: initialRound);
    return ChatEncryptionKey(
      chatId: chatId,
      sessionKey: sessionKey,
      activeKeyRound: initialRound,
      currentRound: initialRound,
      isSingle: isSingle,
    );
  }

  /// 創建同步用的 Map
  Map<String, dynamic> toSyncMap() {
    return {
      'chatId': chatId,
      'activeRound': activeKeyRound,
      'round': currentRound,
      'activeKey': sessionKey.key,
      'isSingle': isSingle,
    };
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is ChatEncryptionKey &&
        other.chatId == chatId &&
        other.sessionKey == sessionKey &&
        other.activeKeyRound == activeKeyRound &&
        other.currentRound == currentRound &&
        other.isSingle == isSingle;
  }

  @override
  int get hashCode => Object.hash(chatId, sessionKey, activeKeyRound, currentRound, isSingle);
}

