package com.zaojiao.app.core.auth.http

import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton

@Singleton
class AuthClient @Inject constructor(
    @Named("timeout") val timeout: Long,
    @Named("endpoint") val endpoint: String,
) {
    private val moshi = Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()

    private val okHttpClient = OkHttpClient.Builder()
        .connectTimeout(timeout, TimeUnit.MILLISECONDS)
        .readTimeout(timeout, TimeUnit.MILLISECONDS)
        .writeTimeout(timeout, TimeUnit.MILLISECONDS)
        .retryOnConnectionFailure(true)
        .followRedirects(false)
        .followSslRedirects(false)
        .build()

    private val retrofit = Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl(endpoint)
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .build()

    private val api = retrofit.create(AuthApi::class.java)

    suspend fun loginBySms(phone: String, code: String) = api.loginBySms(phone, code)

    suspend fun loginByWechat(code: String) = api.loginByWechat(code)

    suspend fun loginByOneClick(token: String) = api.loginByOneClick(token)

    suspend fun refreshToken(refreshToken: String) = api.refreshToken(refreshToken)
}