package com.demotest.app.network

import com.demotest.app.BuildConfig
import com.demotest.app.data.local.AppPreferences
import com.demotest.app.extensions.Constants
import com.demotest.app.network.ApiService
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

val networkModule = module {
    single { provideRetrofit(get()) }
    factory { provideApi(get()) }
}

fun provideRetrofit(pref: AppPreferences): Retrofit {
    val interceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)

    val okHttpClient = OkHttpClient().newBuilder()
        .callTimeout(1, TimeUnit.MINUTES)
        .writeTimeout(1, TimeUnit.MINUTES)
        .readTimeout(1, TimeUnit.MINUTES)
        .addInterceptor(interceptor)
        .addInterceptor(Interceptor { chain ->
            val request: Request =
                chain.request().newBuilder()
                    .addHeader("Content-Type", Constants.CONTENT_TYPE)
                    .addHeader("Authorization", "")
                    .build()
            val response = chain.proceed(request)
            if (response.code == 401) Constants.isAuthorized.postValue(false)
            response
        }).build()

    return Retrofit.Builder().baseUrl(BuildConfig.BASE_URL)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build()


}

fun provideApi(retrofit: Retrofit): ApiService = retrofit.create(ApiService::class.java)
