package com.correx.apps.server.protocol

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

class ProtocolException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)

object ProtocolSerializer {
    private val json = Json {
        classDiscriminator = "type"
        ignoreUnknownKeys = true
    }

    fun encodeServerMessage(msg: ServerMessage): String = json.encodeToString(msg)

    fun decodeClientMessage(json: String): ClientMessage {
        return runCatching {
            this.json.decodeFromString<ClientMessage>(json)
        }.getOrElse { cause ->
            throw ProtocolException("Failed to decode client message", cause)
        }
    }
}
