package app.closer.core.notifications

import android.os.Build
import app.closer.BuildConfig
import app.closer.domain.repository.AuthRepository
import app.closer.domain.repository.UserRepository
import com.google.firebase.messaging.FirebaseMessaging
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Fetches the FCM token and writes it to Firestore with device metadata.
 *
 * Called on app start and after sign-in to ensure the server always has
 * a current token for this device.
 */
@Singleton
class TokenRegistrar @Inject constructor(
    private val authRepository: AuthRepository,
    private val userRepository: UserRepository,
    private val messaging: FirebaseMessaging
) {

    suspend fun register(): Result<Unit> = runCatching {
        val uid = authRepository.currentUserId
            ?: throw IllegalStateException("No authenticated user")

        val token = messaging.token.await()
        val metadata = DeviceMetadata(
            platform = "android",
            osVersion = Build.VERSION.RELEASE ?: "unknown",
            appVersion = BuildConfig.VERSION_NAME,
            sdkVersion = Build.VERSION.SDK_INT,
            timestamp = System.currentTimeMillis()
        )

        userRepository.storeFcmToken(uid, token)
        userRepository.storeTokenMetadata(uid, token, metadata)
    }

    data class DeviceMetadata(
        val platform: String,
        val osVersion: String,
        val appVersion: String,
        val sdkVersion: Int,
        val timestamp: Long
    )
}
