package com.example.design_system.util

import android.util.Log
import android.webkit.JavascriptInterface
import androidx.annotation.Keep
import com.example.core.model.PrintEntity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

@Keep
class PspJavaScriptInterface(
    private val onPayClick: (Long, String?) -> Unit,
    private val onPrintClick: (List<PrintEntity>) -> Unit,
    private val onDeviceInfo: () -> String,
) {

    @JavascriptInterface
    @Keep
    fun pay(amount: Double, id: String?) {
        Log.d("PspBridge", "pay called: amount=$amount, id=$id")
        try {
            onPayClick(amount.toLong(), id)
        } catch (e: Exception) {
            Log.e("PspBridge", "Error in pay callback", e)
        }
    }

    @JavascriptInterface
    @Keep
    fun print(printEntitiesJson: String) {
        Log.d("PspBridge", "print called: $printEntitiesJson")
        try {
            val type = object : TypeToken<List<PrintEntity>>() {}.type
            val list: List<PrintEntity> = Gson().fromJson(printEntitiesJson, type)
            onPrintClick(list)
        } catch (e: Exception) {
            Log.e("PspBridge", "Error parsing print entities", e)
        }
    }

    @JavascriptInterface
    @Keep
    fun deviceInfo(): String {
        Log.d("PspBridge", "uuid called")
        return try {
            onDeviceInfo()
        } catch (e: Exception) {
            Log.e("PspBridge", "Error in uuid callback", e)
            ""
        }
    }
}
