package com.example.defenseapplication.utils

import com.google.gson.Gson
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 统一网络请求封装
 */
object RetrofitNetwork {

    private const val DEFAULT_TIMEOUT = 30L
    const val BASE_URL = "https://stem-boozy-margarine.ngrok-free.dev"

    private var retrofit: Retrofit? = null
    private val gson = Gson()

    /**
     * 动态修改 BaseUrl
     */
    fun setBaseUrl(baseUrl: String) {
        retrofit = createRetrofit(baseUrl)
    }

    fun getNetworkService(): ApiService = getService(ApiService::class.java)

    fun <T> getService(service: Class<T>, baseUrl: String? = null): T {
        if (retrofit == null || baseUrl != null) {
            retrofit = createRetrofit(baseUrl ?: BASE_URL)
        }
        return retrofit!!.create(service)
    }

    /**
     * 专门用于下载的 Service (无日志，防止内存溢出)
     */
    fun createRetrofitDownload(): ApiService {
        return Retrofit.Builder()
            .baseUrl(normalizeBaseUrl(BASE_URL))
            .client(createOkHttpClient(enableLogging = false))
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
            .create(ApiService::class.java)
    }

    private fun createRetrofit(baseUrl: String): Retrofit {
        return Retrofit.Builder()
            .baseUrl(normalizeBaseUrl(baseUrl))
            .client(createOkHttpClient(enableLogging = true))
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
    }

    private fun normalizeBaseUrl(baseUrl: String): String {
        val trimmed = baseUrl.trim()
        return if (trimmed.endsWith("/")) trimmed else "$trimmed/"
    }

    private fun createOkHttpClient(enableLogging: Boolean): OkHttpClient {
        val builder = OkHttpClient.Builder()
            .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .addInterceptor(ApiConfig.createHeadersInterceptor())
            .addInterceptor(ApiConfig.getUnifiedInterceptor()) // 使用 ApiConfig 中的统一拦截器

        if (enableLogging) {
            builder.addInterceptor(ApiConfig.getLoggingInterceptor()) // 使用 ApiConfig 中的日志拦截器
        }

        return builder.build()
    }
}