package app.closer.data.remote

import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.SetOptions
import kotlinx.coroutines.tasks.await
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Stores and retrieves the per-user ECIES public key at
 * users/{userId}/devices/{deviceId}.
 *
 * Only the public key is stored. Private key material never leaves the device.
 * The document is merged (not replaced) so that future multi-device fields can
 * be added without stomping existing data.
 */
@Singleton
class FirestoreDeviceKeyDataSource @Inject constructor(
    private val db: FirebaseFirestore
) {

    suspend fun publishPublicKey(userId: String, publicKeyB64: String) {
        deviceRef(userId)
            .set(
                mapOf(
                    "deviceId" to FirestoreCollections.Users.DEVICE_PRIMARY,
                    "publicKey" to publicKeyB64,
                    "platform" to "android",
                    "updatedAt" to System.currentTimeMillis()
                ),
                SetOptions.merge()
            )
            .await()
    }

    suspend fun getPublicKey(userId: String): String? =
        deviceRef(userId).get().await().getString("publicKey")

    private fun deviceRef(userId: String) =
        db.collection(FirestoreCollections.USERS)
            .document(userId)
            .collection(FirestoreCollections.Users.DEVICES)
            .document(FirestoreCollections.Users.DEVICE_PRIMARY)
}
