package kr.lunaticbum.back.lun.utils

import com.fasterxml.jackson.databind.ObjectMapper
import kr.lunaticbum.back.lun.model.EncryptedPayload
import java.util.Base64
import kotlin.math.max

object PayloadDecoder {

    private fun format(data: String, key: String, type: String): String {
        val divider = "|*-*|$key|*-*|"
        var (odd, even) = data.split(divider).let { it[0] to it[1] }

        when (type) {
            "T1" -> odd = odd.reversed()
            "T2" -> even = even.reversed()
            "T3" -> {
                odd = odd.reversed()
                even = even.reversed()
            }
            else -> { // Default or empty type
                odd = odd.reversed()
                even = even.reversed()
            }
        }

        val result = StringBuilder()
        val maxLength = maxOf(odd.length, even.length)
        for (i in 0 until maxLength) {
            if (i < even.length) result.append(even[i])
            if (i < odd.length) result.append(odd[i])
        }
        return result.toString()
    }

    fun <T> decode(payload: String, clazz: Class<T>, objectMapper: ObjectMapper): T {
        try {
            // 1. Base64 디코딩
            val b64Decoded = String(Base64.getDecoder().decode(payload))

            // 2. 1차 JSON 파싱 (EncryptedPayload)
            val encryptedPayload = objectMapper.readValue(b64Decoded, EncryptedPayload::class.java)

            // 3. 내부 데이터 복원 (Format)
            val originalJson = format(encryptedPayload.data, encryptedPayload.key, encryptedPayload.type)

            // [중요] 복원된 최종 JSON 로그 출력
            println("====== [PayloadDecoder Log Start] ======")
            println("1. EncryptedPayload Data(Scrambled): ${encryptedPayload.data.take(50)}...")
            println("2. Key: '${encryptedPayload.key}', Type: '${encryptedPayload.type}'")
            println("3. Decoded Original JSON: $originalJson")
            println("====== [PayloadDecoder Log End] ======")

            // 4. 최종 객체 변환
            return objectMapper.readValue(originalJson, clazz)
        } catch (e: Exception) {
            e.printStackTrace()
            throw RuntimeException("Payload decoding failed: ${e.message}")
        }
    }
}