package app.closer.core.firebase

import android.content.Context
import app.closer.BuildConfig
import com.google.firebase.FirebaseApp
import com.google.firebase.appcheck.FirebaseAppCheck
import com.google.firebase.appcheck.playintegrity.PlayIntegrityAppCheckProviderFactory
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class FirebaseInitializer @Inject constructor(
    @ApplicationContext private val context: Context
) {

    fun initialize() {
        val appCheck = FirebaseAppCheck.getInstance()
        if (BuildConfig.DEBUG) {
            // Pre-seed the stable registered debug token so every install (emulator or device)
            // uses the same token without needing re-registration in Firebase Console.
            seedDebugToken()
            try {
                val cls = Class.forName(
                    "com.google.firebase.appcheck.debug.DebugAppCheckProviderFactory"
                )
                val factory = cls.getMethod("getInstance").invoke(null)
                    as com.google.firebase.appcheck.AppCheckProviderFactory
                appCheck.installAppCheckProviderFactory(factory)
            } catch (_: Exception) {
                appCheck.installAppCheckProviderFactory(
                    PlayIntegrityAppCheckProviderFactory.getInstance()
                )
            }
        } else {
            appCheck.installAppCheckProviderFactory(
                PlayIntegrityAppCheckProviderFactory.getInstance()
            )
        }
    }

    private fun seedDebugToken() {
        val token = BuildConfig.APP_CHECK_DEBUG_TOKEN
        if (token.isBlank()) return
        try {
            val persistenceKey = FirebaseApp.getInstance().persistenceKey
            val prefsFile = "com.google.firebase.appcheck.debug.store.$persistenceKey"
            context.getSharedPreferences(prefsFile, Context.MODE_PRIVATE)
                .edit()
                .putString("com.google.firebase.appcheck.debug.DEBUG_SECRET", token)
                .commit()
        } catch (_: Exception) {
            // Best effort — debug provider will generate and log a new token if this fails.
        }
    }
}
