package com.isidroid.c23.data.source.network

import android.os.Build
import com.isidroid.c23.BuildConfig
import com.isidroid.c23.data.source.settings.Settings
import com.isidroid.session.repository.SessionRepository
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

private const val HEADER_AUTH = "Authorization"

class AuthInterceptor(private val sessionRepository: SessionRepository) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val token = Settings.authToken

        val request = requestBuilder(
            originalRequest = chain.request(),
            accessToken = token
        ).build()

        val response = chain.proceed(request)

        return when (response.code) {
            401 -> refreshToken(chain, request, response)
            else -> response
        }
    }

    private fun refreshToken(
        chain: Interceptor.Chain,
        request: Request?,
        response: Response
    ): Response {
        if (request == null) return response

        response.close()
//        val newToken = sessionRepository.refreshAuthToken()
        val newToken = ""

        Settings.authToken = newToken

        val builder = request.newBuilder()
            .removeHeader(HEADER_AUTH)
            .addHeader("app-version", BuildConfig.VERSION_NAME)
            .addHeader("os-version", Build.MODEL)
        authorizeCall(builder, newToken)

        return chain.proceed(builder.build())
    }

    private fun requestBuilder(originalRequest: Request, accessToken: String?): Request.Builder {
        val builder = originalRequest.newBuilder()
//        if (request.method == "POST" || request.method == "PUT")
        builder.addHeader("Accept", "application/json")
        val skipAuth = originalRequest.headers.any { it.first == "skip_auth" }

        if (!skipAuth) authorizeCall(builder, accessToken)
        return builder
    }

    private fun authorizeCall(builder: Request.Builder, accessToken: String?) {

        accessToken?.let {
            builder.addHeader("Authorization", "Bearer $accessToken")
//            builder.addHeader("X-Authorization-Token", accessToken)
        }
    }
}