package cy.hexor.furumi.data.repository

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request

@Singleton
class MediaImageLoader @Inject constructor(
    private val okHttpClient: OkHttpClient
) {
    suspend fun load(url: String): Result<Bitmap> {
        return withContext(Dispatchers.IO) {
            runCatching {
                val request = Request.Builder()
                    .url(url)
                    .build()

                okHttpClient.newCall(request).execute().use { response ->
                    if (!response.isSuccessful) {
                        throw IOException("Image request failed with HTTP ${response.code}")
                    }

                    val bytes = response.body?.bytes()
                        ?: throw IOException("Image response is empty")

                    BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                        ?: throw IOException("Image response is not a supported bitmap")
                }
            }
        }
    }
}
