import Foundation

struct Conversation: Identifiable, Equatable {
    let id: String
    var name: String?
    var members: [ConversationMember]
    var createdBy: String?
    var avatarFile: String?
    var unreadCount: Int
    var isFavorite: Bool
    var lastMessageTime: Date?

    var isGroup: Bool {
        name != nil || members.count > 2
    }

    /// Display name: group name, or DM partner username
    func displayName(currentUserId: String) -> String {
        if let name = name, !name.isEmpty {
            return name
        }
        // DM: show the other person's name
        if let other = members.first(where: { $0.userId != currentUserId }) {
            return other.username
        }
        return "Unknown"
    }

    /// DM partner user ID (nil for groups)
    func dmPartnerId(currentUserId: String) -> String? {
        guard !isGroup else { return nil }
        return members.first(where: { $0.userId != currentUserId })?.userId
    }

    static func == (lhs: Conversation, rhs: Conversation) -> Bool {
        lhs.id == rhs.id
    }
}

struct ConversationMember: Identifiable, Equatable, Codable {
    let userId: String
    var username: String
    var email: String

    var id: String { userId }
}
