package space.nstart.pcp.pcp_types_lib.utils.json

import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import space.nstart.pcp.pcp_types_lib.message.KafkaEvent
import space.nstart.pcp.pcp_types_lib.utils.KafkaEventClassDiscoverer

class KafkaEventDeserializer: JsonDeserializer<KafkaEvent?>() {
    private val enumClasses by lazy { KafkaEventClassDiscoverer.discoverKafkaEventEnums() }

    override fun deserialize(p: JsonParser, ctxt: DeserializationContext): KafkaEvent {
        val value = p.valueAsString

        for (enumClass in enumClasses) {
            try {
                enumClass.java.enumConstants
                    ?.find { it.enumCast()?.name == value }
                    ?.let { enumValue -> return enumValue }
            } catch (e: Exception) {
                // Continue to next class
            }
        }

        throw IllegalArgumentException("Unknown KafkaEvent value: $value. Available values: ${getAllPossibleValues()}")
    }

    private fun getAllPossibleValues(): List<String> {
        return enumClasses.flatMap { it.java.enumConstants.mapNotNull { enum -> enum.enumCast()?.name } }
    }
}