import Foundation

// MARK: - System Accounts

enum SystemAccounts {
    static let safePublicKey = Account.safePublicKey
    static let safeTitle = "Safe"
    static let updatesPublicKey = Account.updatesPublicKey
    static let updatesTitle = "Rosetta Updates"
    static let systemKeys: Set<String> = [safePublicKey, updatesPublicKey]

    static func isSystemAccount(_ publicKey: String) -> Bool {
        systemKeys.contains(publicKey)
    }
}

// MARK: - DeliveryStatus

/// Android/Desktop parity: delivery_status is 0/1/2 only.
/// Read status is stored separately in the `is_read` / `read` column.
enum DeliveryStatus: Int, Codable {
    case waiting = 0
    case delivered = 1
    case error = 2
}

// MARK: - Dialog

/// Represents a chat dialog between the current user and an opponent.
/// Mirrors the Android `DialogEntity` Room database model.
struct Dialog: Identifiable, Codable, Equatable {
    let id: String
    let account: String           // My public key (secp256k1 compressed hex)
    let opponentKey: String       // Opponent's public key

    var opponentTitle: String     // Display name
    var opponentUsername: String  // @username

    var lastMessage: String       // Last message preview (decrypted)
    var lastMessageTimestamp: Int64

    var unreadCount: Int
    var isOnline: Bool
    var lastSeen: Int64

    var verified: Int             // 0 = none, 1 = public figure/brand, 2 = Rosetta admin, 3+ = group admin
    var iHaveSent: Bool           // I have sent at least one message (chat vs request)
    var isPinned: Bool
    var isMuted: Bool

    var lastMessageFromMe: Bool
    var lastMessageDelivered: DeliveryStatus
    /// Android parity: separate read flag for last outgoing message.
    var lastMessageRead: Bool

    /// Desktop parity: true when an unread group message mentions the current user.
    var hasMention: Bool = false

    /// Sender public key of the last message (for "Alice: hey" group chat preview).
    var lastMessageSenderKey: String = ""

    // MARK: - Computed

    var isSavedMessages: Bool { opponentKey == account }
    var isGroup: Bool { DatabaseManager.isGroupDialogKey(opponentKey) }

    /// Client-side heuristic matching Android: badge shown if verified > 0 OR isRosettaOfficial.
    var isRosettaOfficial: Bool {
        SystemAccounts.isSystemAccount(opponentKey)
    }

    /// Effective verification level for UI display.
    var effectiveVerified: Int {
        if verified > 0 { return verified }
        if isRosettaOfficial { return 1 }
        return 0
    }

    var avatarColorIndex: Int {
        RosettaColors.avatarColorIndex(for: opponentTitle, publicKey: opponentKey)
    }

    var initials: String {
        if isSavedMessages { return "S" }
        if isGroup { return RosettaColors.groupInitial(name: opponentTitle, publicKey: opponentKey) }
        return RosettaColors.initials(name: opponentTitle, publicKey: opponentKey)
    }
}

