package de.trainingstagebuch.app.utils

import de.trainingstagebuch.app.network.SocketEvent
import de.trainingstagebuch.app.network.SocketEventType
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive

object SocketMessageUtils {
    private val json = Json { ignoreUnknownKeys = true }

    fun parseSocketIoEvent(rawMessage: String): SocketEvent? {
        if (!rawMessage.startsWith("42")) return null
        val payloadText = rawMessage.removePrefix("42")
        val parsed = runCatching { json.parseToJsonElement(payloadText) }.getOrNull() ?: return null
        val arr = parsed as? JsonArray ?: return null
        if (arr.isEmpty()) return null

        val eventName = (arr[0] as? JsonPrimitive)?.content ?: return null
        val payload: JsonElement? = arr.getOrNull(1)
        return SocketEvent(
            type = SocketEventType.fromWireName(eventName),
            rawType = eventName,
            payload = payload
        )
    }

    fun buildAuthMessage(authCode: String, userId: String): String {
        val payload = JsonObject(
            mapOf(
                "authcode" to JsonPrimitive(authCode),
                "userid" to JsonPrimitive(userId)
            )
        )
        return "42[\"auth\",${json.encodeToString(JsonObject.serializer(), payload)}]"
    }

    fun buildJoinClubMessage(clubId: String): String {
        return "42[\"join-club\",\"$clubId\"]"
    }

    fun buildLeaveClubMessage(clubId: String): String {
        return "42[\"leave-club\",\"$clubId\"]"
    }
}
