package swiss.qpq.gajumobile.data.models

import kotlinx.serialization.Serializable

@Serializable
enum class GridsSignType {
    MESSAGE,
    BINARY,
    TX,
    UNKNOWN;

    companion object {
        fun fromString(type: String?): GridsSignType = when (type) {
            "message" -> MESSAGE
            "binary"  -> BINARY
            "tx"      -> TX
            else      -> UNKNOWN
        }
    }

    fun toProtocolString(): String = when (this) {
        MESSAGE -> "message"
        BINARY  -> "binary"
        TX      -> "tx"
        UNKNOWN -> "unknown"
    }
}

@Serializable
data class GridsSignRequest(
    val type: GridsSignType,
    val payload: String,
    val publicId: String?,
    val networkId: String?,
    val grids: Int,
    val chain: String?
)

/**
 * Safely maps a raw Map (typically from ZJ.decode) to a typed GridsSignRequest.
 */
fun Map<String, Any?>.toGridsSignRequest(): GridsSignRequest {
    val gridsVal = when (val g = this["grids"]) {
        is Number -> g.toInt()
        is String -> g.toIntOrNull() ?: 1
        else -> 1
    }
    return GridsSignRequest(
        type = GridsSignType.fromString(this["type"] as? String),
        payload = this["payload"] as? String ?: "",
        publicId = this["public_id"] as? String,
        networkId = this["network_id"] as? String,
        grids = gridsVal,
        chain = this["chain"] as? String
    )
}
