import Foundation

/// Call signaling packet (0x1A / 26).
/// Wire format mirrors desktop/android:
/// `signalType` always first, then short-form for busy/disconnected,
/// otherwise `src`, `dst`, optional `sharedPublic`, optional `roomId`.
enum SignalType: Int, Sendable {
    case call = 0
    case keyExchange = 1
    case activeCall = 2
    case endCall = 3
    case createRoom = 4
    case endCallBecausePeerDisconnected = 5
    case endCallBecauseBusy = 6
}

struct PacketSignalPeer: Packet {
    static let packetId = 0x1A

    var src: String = ""
    var dst: String = ""
    var sharedPublic: String = ""
    var signalType: SignalType = .call
    var roomId: String = ""

    func write(to stream: Stream) {
        stream.writeInt8(signalType.rawValue)
        if signalType == .endCallBecauseBusy || signalType == .endCallBecausePeerDisconnected {
            return
        }
        stream.writeString(src)
        stream.writeString(dst)
        if signalType == .keyExchange {
            stream.writeString(sharedPublic)
        }
        if signalType == .createRoom {
            stream.writeString(roomId)
        }
    }

    mutating func read(from stream: Stream) {
        signalType = SignalType(rawValue: stream.readInt8()) ?? .call
        if signalType == .endCallBecauseBusy || signalType == .endCallBecausePeerDisconnected {
            return
        }
        src = stream.readString()
        dst = stream.readString()
        if signalType == .keyExchange {
            sharedPublic = stream.readString()
        }
        if signalType == .createRoom {
            roomId = stream.readString()
        }
    }
}
