package com.syaroful.agrilinkvocpro.plant_disease_detection_feature.di

import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.network.GeminiApiService
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.repository.PlantDiagnosisRepository
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.data.repository.PlantDiagnosisRepositoryImpl
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.presentation.detail.PlantDiagnosisViewModel
import com.syaroful.agrilinkvocpro.plant_disease_detection_feature.presentation.history.HistoryViewModel
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
import retrofit2.Retrofit

@OptIn(ExperimentalSerializationApi::class)
val diagnosisModule = module {
    single {
        val loggingInterceptor = HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }

        OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .build()
    }

    single {
        val contentType = "application/json".toMediaType()
        val json = Json {
            ignoreUnknownKeys = true
        }

        Retrofit.Builder()
            .baseUrl("https://generativelanguage.googleapis.com/")
            .client(get()) // ambil OkHttpClient dari Koin
            .addConverterFactory(json.asConverterFactory(contentType))
            .build()
    }

    single<GeminiApiService> {
        get<Retrofit>().create(GeminiApiService::class.java)
    }
    single<PlantDiagnosisRepository> { PlantDiagnosisRepositoryImpl(get()) }
    viewModel { PlantDiagnosisViewModel(get(), get()) }
    viewModel { HistoryViewModel(get()) }
}