package dev.adriankuta.model.data.api.di

import com.squareup.moshi.Moshi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dev.adriankuta.model.data.api.AirportService
import dev.adriankuta.model.data.api.FlightService
import dev.adriankuta.model.data.api.RoutesService
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import javax.inject.Qualifier
import javax.inject.Singleton

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

    @Singleton
    @Provides
    fun provideMoshi() = Moshi.Builder().build()

    @Singleton
    @Provides
    fun provideHttpLoggingInterceptor() = HttpLoggingInterceptor().apply {
        setLevel(HttpLoggingInterceptor.Level.BODY)
    }

    @Singleton
    @Provides
    fun providesOkHttpClient(loggingInterceptor: HttpLoggingInterceptor) =
        OkHttpClient.Builder().also { builder ->
            builder.addInterceptor(loggingInterceptor)
        }.build()

    @Singleton
    @Provides
    @ServicesAPI
    fun provideServicesRetrofit(client: OkHttpClient, moshi: Moshi): Retrofit = Retrofit.Builder()
        // TODO("add URL provided in the task instructions")
        .baseUrl("https://services-api.ryanair.com")
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .client(client)
        .build()

    @Singleton
    @Provides
    @NativeAppsAPI
    fun provideNativeAppsRetrofit(client: OkHttpClient, moshi: Moshi): Retrofit = Retrofit.Builder()
        // TODO("add URL provided in the task instructions")
        .baseUrl("https://nativeapps.ryanair.com")
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .client(client)
        .build()

    @Singleton
    @Provides
    fun provideAirportService(@ServicesAPI retrofit: Retrofit): AirportService =
        retrofit.create(AirportService::class.java)

    @Singleton
    @Provides
    fun provideRoutesService(@ServicesAPI retrofit: Retrofit): RoutesService =
        retrofit.create(RoutesService::class.java)

    @Singleton
    @Provides
    fun provideFlightService(@NativeAppsAPI retrofit: Retrofit): FlightService =
        retrofit.create(FlightService::class.java)
}

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class ServicesAPI

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class NativeAppsAPI
