/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package com.runicgateway.app.core.net

import com.runicgateway.app.core.auth.SessionManager
import okhttp3.Interceptor
import okhttp3.Response
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Attaches the current bearer access token to outbound calls (PLAN.md §4.1).
 * Public endpoints simply carry a token the backend ignores; the credential
 * endpoints (login/refresh) tag themselves [Http.NO_SESSION_HEADER] and are left
 * bare so a credential `401` is never mistaken for an expired session. A request
 * that already set its own Authorization (the authenticator's retry) is untouched.
 */
@Singleton
class AuthInterceptor @Inject constructor(
    private val sessionManager: SessionManager,
) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        if (request.header(Http.NO_SESSION_HEADER) != null) {
            return chain.proceed(request)
        }
        if (request.header(Http.AUTHORIZATION) != null) {
            return chain.proceed(request)
        }
        val token = sessionManager.currentAccessToken()
            ?: return chain.proceed(request)
        val authed = request.newBuilder()
            .header(Http.AUTHORIZATION, Http.bearer(token))
            .build()
        return chain.proceed(authed)
    }
}
