package app.closer.data.remote

import android.net.Uri
import com.google.firebase.storage.FirebaseStorage
import kotlinx.coroutines.suspendCancellableCoroutine
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

@Singleton
class FirebaseStorageDataSource @Inject constructor() {

    private val storage = FirebaseStorage.getInstance()

    suspend fun uploadProfilePhoto(uid: String, uri: Uri): String =
        suspendCancellableCoroutine { cont ->
            val ref = storage.reference.child("users/$uid/profile.jpg")
            ref.putFile(uri)
                .continueWithTask { ref.downloadUrl }
                .addOnSuccessListener { cont.resume(it.toString()) }
                .addOnFailureListener { cont.resumeWithException(it) }
        }
}
