package com.miya.fastcashier.net

import com.miya.fastcashier.net.ApiConfig.getAuthorization
import com.miya.fastcashier.net.ApiService.Companion.wrapUrl
import com.miya.fastcashier.service.AccountService.getAccountInfo
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 requestUrl = original.url.toString()
        val requestBuilder: Request.Builder = original.newBuilder()
        val accountInfo = getAccountInfo()
        if (accountInfo != null && accountInfo.accessToken != null) {
            val loginUrl = wrapUrl(ApiService.LOGIN)
            if (requestUrl != loginUrl) {
                requestBuilder.addHeader(
                    AUTHORIZATION,
                    getAuthorization(accountInfo.accessToken.accessToken)
                )
            }
        }
        val request: Request = requestBuilder.build()
        return chain.proceed(request)
    }
}