package com.seven.ikar.kotlin.ui

import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import coil.compose.AsyncImage
import coil.request.CachePolicy
import coil.request.ImageRequest

@Composable
fun AuthenticatedAsyncImage(
    imageUrl: String?,
    accessToken: String? = null,
    contentDescription: String,
    modifier: Modifier = Modifier,
    contentScale: ContentScale = ContentScale.Crop
) {
    if (imageUrl.isNullOrBlank()) {
        return
    }

    val resolvedAccessToken = accessToken ?: LocalIkarAccessToken.current
    val context = LocalContext.current
    val request = remember(imageUrl, resolvedAccessToken) {
        ImageRequest.Builder(context)
            .data(imageUrl)
            .diskCacheKey(imageUrl)
            .diskCachePolicy(CachePolicy.ENABLED)
            .memoryCachePolicy(CachePolicy.ENABLED)
            .apply {
                if (!resolvedAccessToken.isNullOrBlank()) {
                    addHeader("Authorization", "Bearer $resolvedAccessToken")
                }
            }
            .crossfade(true)
            .build()
    }

    AsyncImage(
        model = request,
        contentDescription = contentDescription,
        modifier = modifier,
        contentScale = contentScale
    )
}
