package com.fastest.pass.app

import android.content.Context
import com.fastest.pass.helpers.BasePreferenceHelper
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class) // Singleton scope for app-wide use
object AppModule {

    // Provide the Base URL here
    private const val BASE_URL = "https://api.fastestpass.com/v1/"
    private const val KEY_HEADER_AUTHORIZATION: String = "Authorization"

    @Provides
    @Singleton
    fun provideOkHttpClient(basePreferenceHelper: BasePreferenceHelper): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(120, TimeUnit.SECONDS)
            .readTimeout(120, TimeUnit.SECONDS)
            .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY })
            .addInterceptor { chain ->
                val token = basePreferenceHelper.getToken()
                val request = chain.request().newBuilder()
                    .addHeader(KEY_HEADER_AUTHORIZATION, "Bearer $token")
                    .build()
                chain.proceed(request)
            }
            .build()
    }

    @Provides
    @Singleton
    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .baseUrl(BASE_URL) // Centralized base URL
            .client(okHttpClient) // Use the OkHttpClient provided above
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    @Provides
    @Singleton
    fun provideBasePreferenceHelper(@ApplicationContext context: Context) : BasePreferenceHelper {
        return BasePreferenceHelper(context)
    }
}