package lu.rewardflow.terminal.data.network

import kotlinx.coroutines.runBlocking
import lu.rewardflow.terminal.data.repository.DeviceConfigRepository
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Response
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Per-request rewrite that pins the host to the device's paired ``api_url``
 * and adds the long-lived ``Authorization: Bearer <auth_token>`` header.
 *
 * Retrofit is built with a placeholder baseUrl because the real URL only
 * exists after pairing — this interceptor is what makes every call actually
 * go to the merchant's chosen server. When the device hasn't been paired
 * yet, requests pass through unchanged and will fail at the network layer
 * (which is fine: the only flows running pre-pairing are the setup-screen
 * verification call, which fills in the URL itself before invoking the API).
 *
 * `runBlocking` is intentional: OkHttp interceptors run on the IO dispatcher
 * pool and DataStore reads are cheap. The alternative (a non-suspend cache)
 * is more code for negligible gain.
 */
@Singleton
class AuthInterceptor @Inject constructor(
    private val configRepository: DeviceConfigRepository,
) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val original = chain.request()
        val (apiUrl, authToken) = runBlocking {
            configRepository.currentApiUrl() to configRepository.currentAuthToken()
        }

        val builder = original.newBuilder()

        if (apiUrl != null) {
            val configuredHost = apiUrl.toHttpUrlOrNull()
            if (configuredHost != null) {
                val rewritten = original.url.newBuilder()
                    .scheme(configuredHost.scheme)
                    .host(configuredHost.host)
                    .port(configuredHost.port)
                    .build()
                builder.url(rewritten)
            }
        }

        if (!authToken.isNullOrBlank()) {
            builder.header("Authorization", "Bearer $authToken")
        }

        return chain.proceed(builder.build())
    }
}
