package top.yeij.cyrene.data.remote

import android.util.Log
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Response

class DynamicUrlInterceptor : Interceptor {

    companion object {
        private const val TAG = "DynamicUrlInterceptor"
    }

    @Volatile
    var baseUrl: String = "http://10.0.2.2:8080/"

    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        val originalUrl = originalRequest.url

        val targetBase = baseUrl.trimEnd('/')
        val parsed = targetBase.toHttpUrlOrNull()
        if (parsed == null) {
            Log.e(TAG, "Invalid baseUrl: '$baseUrl'")
            return chain.proceed(chain.request())
        }

        val newUrl = originalUrl.newBuilder()
            .scheme(parsed.scheme)
            .host(parsed.host)
            .port(parsed.port)
            .build()

        Log.d(TAG, "Rewriting ${originalUrl} → $newUrl (base: $targetBase)")
        return chain.proceed(originalRequest.newBuilder().url(newUrl).build())
    }
}
