package com.jiooption.trading.billing

import android.util.Log
import com.android.billingclient.api.Purchase
import com.jiooption.trading.network.ApiClient
import com.jiooption.trading.network.models.GooglePlayVerifyRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * Repository that bridges Google Play purchases with server-side verification
 */
class BillingRepository {

    companion object {
        private const val TAG = "BillingRepository"
    }

    /**
     * Verify a Google Play purchase on the server and credit the user's wallet
     *
     * @param purchase The completed Google Play purchase
     * @return Pair(success, message)
     */
    suspend fun verifyPurchase(purchase: Purchase): Pair<Boolean, String> {
        return withContext(Dispatchers.IO) {
            try {
                val productId = purchase.products.firstOrNull() ?: ""
                val orderId = purchase.orderId ?: ""

                Log.d(TAG, "Verifying purchase: product=$productId, order=$orderId")

                val request = GooglePlayVerifyRequest(
                    purchaseToken = purchase.purchaseToken,
                    productId = productId,
                    orderId = orderId
                )

                val response = ApiClient.getApiService().verifyGooglePlayPurchase(request)

                if (response.isSuccessful) {
                    val body = response.body()
                    if (body?.success == true) {
                        Log.d(TAG, "Purchase verified successfully")
                        Pair(true, body.message ?: "Deposit successful!")
                    } else {
                        val errorMsg = body?.error ?: body?.message ?: "Verification failed"
                        Log.e(TAG, "Verification failed: $errorMsg")
                        Pair(false, errorMsg)
                    }
                } else {
                    val errorMsg = "Server error: ${response.code()}"
                    Log.e(TAG, errorMsg)
                    Pair(false, errorMsg)
                }
            } catch (e: Exception) {
                Log.e(TAG, "Verification exception", e)
                Pair(false, "Network error: ${e.message}")
            }
        }
    }
}
