package com.jordanbot.autoride.subscription

import android.content.Context
import android.util.Log
import com.jordanbot.autoride.api.ApiClient
import com.jordanbot.autoride.api.CheckSubscriptionRequest
import com.jordanbot.autoride.utils.DeviceUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object SubscriptionManager {
    private const val PREFS_NAME = "SubscriptionPrefs"
    private const val KEY_PLAN = "plan"
    private const val KEY_CAN_ACCEPT = "can_accept"
    private const val KEY_RIDES_TODAY = "rides_today"
    private const val KEY_RIDES_LIMIT = "rides_limit"

    var currentPlan: String = "free"
    var canAcceptRides: Boolean = true
    var ridesToday: Int = 0
    var ridesLimit: Int = 1

    fun loadLocalCache(context: Context) {
        val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        currentPlan = prefs.getString(KEY_PLAN, "free") ?: "free"
        canAcceptRides = prefs.getBoolean(KEY_CAN_ACCEPT, true)
        ridesToday = prefs.getInt(KEY_RIDES_TODAY, 0)
        ridesLimit = prefs.getInt(KEY_RIDES_LIMIT, 1)
    }

    suspend fun checkSubscription(context: Context): Boolean {
        return withContext(Dispatchers.IO) {
            try {
                val fingerprint = DeviceUtils.getDeviceFingerprint(context)
                val response = ApiClient.service.checkSubscription(CheckSubscriptionRequest(fingerprint))
                
                if (response.success) {
                    currentPlan = response.plan ?: "free"
                    canAcceptRides = response.can_accept ?: false
                    ridesToday = response.rides_today ?: 0
                    ridesLimit = response.rides_limit ?: 1

                    // Save to cache
                    val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                    prefs.edit().apply {
                        putString(KEY_PLAN, currentPlan)
                        putBoolean(KEY_CAN_ACCEPT, canAcceptRides)
                        putInt(KEY_RIDES_TODAY, ridesToday)
                        putInt(KEY_RIDES_LIMIT, ridesLimit)
                        apply()
                    }
                    Log.d("JordanBot", "Subscription checked: $currentPlan, canAccept: $canAcceptRides")
                    return@withContext true
                }
            } catch (e: Exception) {
                Log.e("JordanBot", "Failed to check subscription", e)
            }
            return@withContext false
        }
    }
}
