package com.crm.chat.data.api

import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class ApiClient(private val baseUrl: String, private val apiKey: String? = null, private val token: String? = null) {

    private val okHttpClient: OkHttpClient by lazy {
        val loggingInterceptor = HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }

        val builder = OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)

        // Add API key interceptor if API key is provided
        if (!apiKey.isNullOrBlank()) {
            val apiKeyInterceptor = Interceptor { chain ->
                val request = chain.request().newBuilder()
                    .addHeader("x-api-key", apiKey)
                    .build()
                chain.proceed(request)
            }
            builder.addInterceptor(apiKeyInterceptor)
        }

        // Add auth token interceptor if token is provided
        if (!token.isNullOrBlank()) {
            val authInterceptor = Interceptor { chain ->
                val request = chain.request().newBuilder()
                    .addHeader("Authorization", "Bearer $token")
                    .build()
                chain.proceed(request)
            }
            builder.addInterceptor(authInterceptor)
        }

        builder.build()
    }

    private val retrofit: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    val authApiService: AuthApiService by lazy {
        retrofit.create(AuthApiService::class.java)
    }

    val chatApiService: ChatApiService by lazy {
        retrofit.create(ChatApiService::class.java)
    }

    val userApiService: UserApiService by lazy {
        retrofit.create(UserApiService::class.java)
    }

    val userProfileApiService: UserProfileApiService by lazy {
        retrofit.create(UserProfileApiService::class.java)
    }

    // Expose OkHttpClient for file uploads
    fun getOkHttpClientInstance(): OkHttpClient = okHttpClient

    // Expose baseUrl for file uploads
    fun getBaseUrl(): String = baseUrl

    // Expose apiKey for file uploads
    fun getApiKey(): String? = apiKey

    // Expose token for file downloads
    fun getToken(): String? = token
}
