import Foundation

/// 信令消息（JSON），与 WebRTCSignalServer 的 SignalMessage 字段一一对应。
/// type: REGISTER / OFFER / ANSWER / ICE_CANDIDATE / TARGET_OFFLINE /
///       CONNECTION_REJECTED / REQUEST_ERROR / REQUEST_TIMEOUT / REGISTER_SUCCESS 等
struct SignalMessage: Codable {
    var type: String?
    var fromDeviceId: String?
    var toDeviceId: String?
    var deviceType: String?
    /// payload 为字符串形式的 JSON（如 {"sdp": "..."}），与服务端约定一致
    var payload: String?
    var authType: String?
    var authValue: String?

    init(type: String? = nil,
         fromDeviceId: String? = nil,
         toDeviceId: String? = nil,
         deviceType: String? = nil,
         payload: String? = nil,
         authType: String? = nil,
         authValue: String? = nil) {
        self.type = type
        self.fromDeviceId = fromDeviceId
        self.toDeviceId = toDeviceId
        self.deviceType = deviceType
        self.payload = payload
        self.authType = authType
        self.authValue = authValue
    }

    /// 解析 payload 字符串为 JSON 字典
    func payloadJSON() -> [String: Any]? {
        guard let payload, let data = payload.data(using: .utf8) else { return nil }
        return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
    }

    /// 将字典序列化为 payload 字符串
    static func encodePayload(_ dict: [String: Any]) -> String? {
        guard let data = try? JSONSerialization.data(withJSONObject: dict) else { return nil }
        return String(data: data, encoding: .utf8)
    }
}
