package com.github.nullptroma.wallenc.domain.vault.network.yandexdisk

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory
import java.io.IOException

object YandexDiskRepositoryTestFactory {

    private val jackson = jacksonObjectMapper().findAndRegisterModules()

    fun createApi(
        baseUrl: String,
        tokenProvider: () -> String?,
    ): YandexDiskApi {
        val client = OkHttpClient.Builder()
            .addInterceptor { chain ->
                val token = tokenProvider()
                    ?: throw IOException("Yandex OAuth token is missing")
                chain.proceed(
                    chain.request().newBuilder()
                        .header("Authorization", "OAuth $token")
                        .build(),
                )
            }
            .build()
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(client)
            .addConverterFactory(JacksonConverterFactory.create(jackson))
            .build()
            .create(YandexDiskApi::class.java)
    }
}
