package cy.hexor.furumi.data.remote

import cy.hexor.furumi.data.local.AuthSessionStorage
import okhttp3.Interceptor
import okhttp3.Response
import javax.inject.Inject

class AccessTokenInterceptor @Inject constructor(
    private val sessionStorage: AuthSessionStorage,
    private val authEndpoints: AuthEndpoints,
    private val appClientInfo: AppClientInfo
) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val baseRequest = request.newBuilder()
            .header(HEADER_USER_AGENT, appClientInfo.userAgent)
            .build()

        if (baseRequest.header(HEADER_AUTHORIZATION) != null ||
            authEndpoints.isLoginOrRefreshPath(baseRequest.url.encodedPath)
        ) {
            return chain.proceed(baseRequest)
        }

        val tokens = sessionStorage.getTokens() ?: return chain.proceed(baseRequest)
        val authorizedRequest = baseRequest.newBuilder()
            .header(HEADER_AUTHORIZATION, tokens.authorizationHeader)
            .build()

        return chain.proceed(authorizedRequest)
    }

    companion object {
        const val HEADER_AUTHORIZATION = "Authorization"
        const val HEADER_USER_AGENT = "User-Agent"
    }
}
