# AuthInterceptor.kt

    /*
     * The MIT License
     *
     * Original work sponsored and donated by The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     * Copyright (C) 2021 The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     *
     * Permission is hereby granted, free of charge, to any person obtaining a copy of
     * this software and associated documentation files (the "Software"), to deal in
     * the Software without restriction, including without limitation the rights to
     * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
     * of the Software, and to permit persons to whom the Software is furnished to do
     * so, subject to the following conditions:
     *
     *
     * The above copyright notice and this permission notice shall be included in all
     * copies or substantial portions of the Software.
     *
     *
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
     * SOFTWARE.
     */

    package dk.nsp.api.util

    import dk.nsp.api.auth.AuthController
    import dk.nsp.mingraviditet.api.BuildConfig
    import dk.nsp.shared.Failed
    import dk.nsp.shared.Success
    import kotlinx.coroutines.runBlocking
    import okhttp3.Interceptor
    import okhttp3.Request
    import okhttp3.Response
    import timber.log.Timber

    class AuthInterceptor(private val authController: AuthController) : Interceptor {

        private val authHeaderKey = "Authorization"
        private val platformHeaderKey = "X-NSP-GM-Platform"
        private val authType = "Bearer"

        private val platformKey =
            "Android_${BuildConfig.ANDROID_APP_VERSION_NAME}(${BuildConfig.ANDROID_APP_VERSION_CODE})"

        override fun intercept(chain: Interceptor.Chain): Response {
            return attachAuthToken(chain)
        }

        private fun attachAuthToken(chain: Interceptor.Chain): Response {
            val token = getTokenBlocking()
            val builder = chain.request().newBuilder()

            builder.setHeader(platformHeaderKey, platformKey)
            builder.setHeader(authHeaderKey, "$authType $token")

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

        private fun getTokenBlocking(): String? = runBlocking {
            if (!authController.isLoggedIn()) {
                Timber.e("User is not logged in")
                null
            } else {
                when (val accessToken = authController.getAccessToken()) {
                    is Success -> accessToken.value
                    is Failed -> {
                        Timber.e(accessToken.error, "Could not get access token")
                        null
                    }
                }
            }
        }

        // Use this to avoid duplicates of the same header
        private fun Request.Builder.setHeader(headerKey: String, value: String) {
            removeHeader(headerKey)
            addHeader(headerKey, value)
        }
    }