package com.isidroid.job.di

import android.content.Context
import com.google.gson.Gson
import com.isidroid.core.DiDebuggableBuild
import com.isidroid.core.DiMock
import com.isidroid.job.data.source.local.JobDao
import com.isidroid.job.data.source.local.JobLocalSource
import com.isidroid.job.data.source.remote.JobNetworkSource
import com.isidroid.job.data.source.remote.MockInterceptor
import com.isidroid.job.data.source.remote.api.ApiJob
import com.isidroid.job.repository.JobRepository
import com.isidroid.job.repository.JobRepositoryImpl
import com.isidroid.network.ApiCacheControlInterceptor
import com.isidroid.network.ApiServerUrl
import com.isidroid.network.ApiTokenInterceptor
import com.isidroid.network.createRetrofitApiClient
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import okhttp3.Interceptor
import okhttp3.logging.HttpLoggingInterceptor
import javax.inject.Qualifier
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
internal object JobModule {
    @Provides @Singleton
    fun provideJobNetworkSource(api: ApiJob) = JobNetworkSource(api)

    @Provides @Singleton
    fun provideJobLocalSource(dao: JobDao) = JobLocalSource(dao)



    @Provides @Singleton
    fun provideJobRepository(
        @ApplicationContext context: Context,
        jobNetworkSource: JobNetworkSource,
        jobLocalSource: JobLocalSource,
    ): JobRepository = JobRepositoryImpl(jobNetworkSource, jobLocalSource)

    @Provides @DiJobMockInterceptor
    fun provideMockInterceptor(
        @ApplicationContext context: Context,
        @DiMock isMock: Boolean
    ): Interceptor = MockInterceptor(context, isMock)

    @Singleton @Provides
    fun provideApiJob(
        @ApiServerUrl serverUrl: String,
        @DiDebuggableBuild isDebugBuild: Boolean,
        @ApiTokenInterceptor authInterceptor: Interceptor,
        @DiJobMockInterceptor mockInterceptor: Interceptor,
        @ApiCacheControlInterceptor cacheInterceptor: Interceptor,
        gson: Gson
    ) = createRetrofitApiClient(
        baseUrl = serverUrl,
        cl = ApiJob::class.java,
        logLevel = HttpLoggingInterceptor.Level.BODY,
        gson = gson,
        isDebugBuild = isDebugBuild,
        interceptors = listOf(authInterceptor, mockInterceptor, cacheInterceptor)
    )
}

@Qualifier
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY, AnnotationTarget.VALUE_PARAMETER)
internal annotation class DiJobMockInterceptor