package com.example.initiateaphonecallapp.data.network

import com.example.initiateaphonecallapp.manager.TokenManager
import com.google.gson.GsonBuilder
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitClient {
    private const val BASE_URL = "http://120.26.58.34/prod-api/"
//    private const val BASE_URL = "http://121.43.240.248/prod-api/"

    // 创建日志拦截器
    private val loggingInterceptor = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    }

    // 创建一个拦截器，用于在请求头中添加 token
    private val authInterceptor = Interceptor { chain ->
        val originalRequest = chain.request()
        val token = TokenManager.getToken()

        val newRequest = if (!token.isNullOrEmpty()) {
            originalRequest.newBuilder()
                .addHeader("Authorization", "Bearer $token")
                .build()
        } else {
            originalRequest
        }

        chain.proceed(newRequest)
    }

    // 创建 OkHttpClient
    private val okHttpClient = OkHttpClient.Builder()
        .addInterceptor(loggingInterceptor)
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS)
        .addInterceptor(authInterceptor) // 添加认证拦截器
        .build()

    // 创建 Gson 实例
    private val gson = GsonBuilder()
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
        .create()

    // 创建 Retrofit 实例
    private val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build()

    val loginApiService: LoginApiService by lazy {
        retrofit.create(LoginApiService::class.java)
    }

    val uploadFileApiService: UploadFile by lazy {
        retrofit.create(UploadFile::class.java)
    }
    val apiCallLogService: ApiCallLogService by lazy {
        retrofit.create(ApiCallLogService::class.java)
    }
    val apiContactsService: ApiContactsService by lazy {
        retrofit.create(ApiContactsService::class.java)
    }
    val pipelineService: PipelineService by lazy {
        retrofit.create(PipelineService::class.java)
    }
}