package com.jiooption.trading.network

import com.jiooption.trading.App
import com.jiooption.trading.security.SSLPinning
import com.jiooption.trading.utils.Constants
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * Retrofit API client singleton
 */
object ApiClient {

    private var retrofit: Retrofit? = null
    private var apiService: ApiService? = null

    fun getClient(): Retrofit {
        if (retrofit == null) {
            val loggingInterceptor = HttpLoggingInterceptor().apply {
                level = if (com.jiooption.trading.BuildConfig.DEBUG) {
                    HttpLoggingInterceptor.Level.BODY
                } else {
                    HttpLoggingInterceptor.Level.NONE
                }
            }

            val clientBuilder = OkHttpClient.Builder()
                .connectTimeout(Constants.CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(Constants.READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(Constants.WRITE_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(AuthInterceptor(App.getSecureStorage()))
                .addInterceptor(loggingInterceptor)

            // Add SSL pinning for production
            if (SSLPinning.isEnabled()) {
                clientBuilder.certificatePinner(SSLPinning.createCertificatePinner())
            }

            val client = clientBuilder.build()

            retrofit = Retrofit.Builder()
                .baseUrl(Constants.API_URL + "/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }

        return retrofit!!
    }

    fun getApiService(): ApiService {
        if (apiService == null) {
            apiService = getClient().create(ApiService::class.java)
        }
        return apiService!!
    }

    /**
     * Reset the client (e.g., when base URL changes)
     */
    fun reset() {
        retrofit = null
        apiService = null
    }
}
