import Testing
import Foundation
@testable import TetherKit

@Suite("Message wire format")
struct MessageTests {
    @Test("decodes a server clipboard frame")
    func decodeClipboard() throws {
        let json = #"{"type":"clipboard","text":"hello","from":"peerA","source":"macos-chrome","room":"a1b2c3d4","ts":1718900000000}"#
        let m = try JSONDecoder().decode(Message.self, from: Data(json.utf8))
        #expect(m.type == .clipboard)
        #expect(m.text == "hello")
        #expect(m.room == "a1b2c3d4")
        #expect(m.ts == 1_718_900_000_000)
    }

    @Test("omits empty fields like the Go omitempty tags")
    func encodeOmitsEmpty() throws {
        let m = Message.clipboard("hi", room: "room1", from: "me")
        let data = try JSONEncoder().encode(m)
        let obj = try JSONSerialization.jsonObject(with: data) as! [String: Any]
        #expect(obj["type"] as? String == "clipboard")
        #expect(obj["text"] as? String == "hi")
        #expect(obj["to"] == nil)      // never set → must not serialize
        #expect(obj["signal"] == nil)
    }

    @Test("preserves an opaque WebRTC signal blob")
    func roundTripSignal() throws {
        let json = #"{"type":"signal","from":"p","signal":{"sdp":"v=0","candidates":[1,2]},"ts":1}"#
        let m = try JSONDecoder().decode(Message.self, from: Data(json.utf8))
        #expect(m.type == .signal)
        let re = try JSONEncoder().encode(m)
        let back = try JSONDecoder().decode(Message.self, from: re)
        #expect(back.signal == m.signal)
    }
}
