import Foundation
import MessagePack

// MARK: - Chat Buffer

struct ChatBuffer: Identifiable, Sendable, Decodable {
    let name: String
    let canSend: Bool

    var id: String { name }

    var displayName: String {
        switch name {
        case "global": "Global"
        case "map": "Map"
        case "debug": "Debug"
        case "direct-messages": "DMs"
        default: name.capitalized
        }
    }

    init(name: String, canSend: Bool) {
        self.name = name
        self.canSend = canSend
    }

    init(from decoder: Decoder) throws {
        var c = try decoder.unkeyedContainer()
        name = try c.decode(String.self)
        canSend = c.isAtEnd ? false : try c.decode(Bool.self)
    }
}

// MARK: - Chat Message

struct ChatMessage: Identifiable, Sendable, Decodable {
    let id: String
    let buffer: String
    let senderId: String?
    let senderName: String
    let content: String
    let isInteractable: Bool
    let senderIsRecipient: Bool
    let isSystem: Bool
    let timestamp: Date

    init(from decoder: Decoder) throws {
        var c = try decoder.unkeyedContainer()
        buffer = try c.decode(String.self)                                          // [0]
        _ = try c.decodeNil() ? nil : c.decode(String.self)                          // [1] server msg ID (not unique)
        id = UUID().uuidString
        senderId = try c.decodeNil() ? nil : c.decode(String.self)                  // [2]
        senderName = try c.decode(String.self)                                      // [3]
        isInteractable = try c.decode(Bool.self)                                    // [4]
        content = try c.decode(String.self)                                         // [5]
        _ = c.isAtEnd ? nil : try (c.decodeNil() ? nil : c.decode(String.self))     // [6] sound
        senderIsRecipient = c.isAtEnd ? false : try c.decode(Bool.self)             // [7]
        isSystem = false
        timestamp = .now
    }

    /// Create a system message (from Say packets)
    init(systemMessage: String) {
        self.id = UUID().uuidString
        self.buffer = "system"
        self.senderId = nil
        self.senderName = "System"
        self.content = systemMessage
        self.isInteractable = false
        self.senderIsRecipient = false
        self.isSystem = true
        self.timestamp = .now
    }
}
