package com.waytous.anticollision.di

import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.waytous.anticollision.data.api.ApiConstants
import com.waytous.anticollision.data.api.MapApiService
import com.waytous.anticollision.repository.MainRepository
import com.waytous.anticollision.ui.MainViewModel
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

@InstallIn(SingletonComponent::class)
@Module
object NetworkModule {

    @Provides
    fun provideHttpLoggingInterceptor() =
        HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BASIC }

    @Provides
    fun provideOkHttpClient(logger: HttpLoggingInterceptor) = OkHttpClient.Builder()
        .addInterceptor(logger)
        .connectTimeout(120,TimeUnit.SECONDS)
        .readTimeout(120,TimeUnit.SECONDS)
        .build()

    @Provides
    fun provideRetrofit(client: OkHttpClient): Retrofit = Retrofit.Builder()
        .baseUrl(ApiConstants.BASE_ENDPOINT)
        .client(client)
        .addConverterFactory(
            MoshiConverterFactory.create(
                Moshi.Builder()
                    .add(KotlinJsonAdapterFactory())
                    .build()
            )
        )
        .addConverterFactory(ScalarsConverterFactory.create())
        .build()

    @Provides
    fun provideMapApiService(retrofit: Retrofit): MapApiService = retrofit.create(MapApiService::class.java)
    @Provides
    fun provideMainRepository(mapApiService: MapApiService):MainRepository = MainRepository(mapApiService)
    @Provides
    fun provideMainViewModel(repository: MainRepository) = MainViewModel(repository)
}