package app.closer.data.remote

import android.content.Context
import android.net.Uri
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageMetadata
import dagger.hilt.android.qualifiers.ApplicationContext
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(
    @ApplicationContext private val context: Context
) {

    private val storage = FirebaseStorage.getInstance()

    suspend fun uploadProfilePhoto(uid: String, uri: Uri): String =
        suspendCancellableCoroutine { cont ->
            val ref = storage.reference.child("users/$uid/profile.jpg")
            val mimeType = context.contentResolver.getType(uri)
                ?.takeIf { it.startsWith("image/") }
                ?: "image/jpeg"
            val metadata = StorageMetadata.Builder()
                .setContentType(mimeType)
                .build()
            ref.putFile(uri, metadata)
                .continueWithTask { ref.downloadUrl }
                .addOnSuccessListener { cont.resume(it.toString()) }
                .addOnFailureListener { cont.resumeWithException(it) }
        }
}
