/*
 * Copyright (c) 2026 QPQ IaaS AG <info@qpq.swiss>. All rights reserved.
 * Project: Gajumaru Core Java Libraries <gajumaru.io>
 *
 * This program is dual-licensed:
 * 1) Under the GNU Affero General Public License as published by the Free
 *    Software Foundation, either version 3 of the License, or (at your option)
 *    any later version (AGPL-3.0-or-later).
 *
 * 2) Under a commercial/proprietary license available directly from QPQ IaaS AG.
 *    If you wish to use this software outside the strict constraints of the
 *    AGPLv3 (e.g. within a closed-source or proprietary product), you must
 *    purchase a commercial license from QPQ IaaS AG.
 *
 * Authors:
 *   - Craig Everett <craigeverett@qpq.swiss>
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later OR LicenseRef-QPQ-Commercial
 */

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
    )
}
