package com.fastcashier.lib_common.net

import com.fastcashier.lib_common.function.account.AccountService.getAccountInfo
import com.fastcashier.lib_common.net.ApiConfig.getAuthorization
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

/**
 * 签名拦截器
 * 添加请求头校验 AUTHORIZATION
 */
class RequestSignInterceptor : Interceptor {

    companion object {
        private const val AUTHORIZATION = "Authorization"
    }

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val original: Request = chain.request()
        val requestBuilder: Request.Builder = original.newBuilder()
        val accountInfo = getAccountInfo()
        if (accountInfo != null && accountInfo.accessToken != null) {
            requestBuilder.addHeader(
                AUTHORIZATION,
                getAuthorization(accountInfo.accessToken.accessToken)
            )
        }
        val request: Request = requestBuilder.build()
        return chain.proceed(request)
    }
}