package com.doverfuelingsolutions.issp.api.basic

import com.doverfuelingsolutions.issp.utils.log.DFSLog
import okhttp3.Interceptor
import okhttp3.Response

class LoggingInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val time = System.currentTimeMillis()

        val requestName = request.header("requestName")
        val requestBuilder = request.newBuilder()
        requestBuilder.removeHeader("requestName")
        val newRequest = requestBuilder.build()

        DFSLog.v("=====>>>>> request[$requestName]: ${newRequest.method()} ${newRequest.url()}")
        val response = chain.proceed(newRequest)
        val body = response.body()
        val stringBody = if (body == null) "null" else response.peekBody(Long.MAX_VALUE).string()
        DFSLog.v(
            "=====>>>>> request[$requestName] done: ${System.currentTimeMillis() - time}ms",
            "code = ${response.code()}",
            "body = $stringBody"
        )
        return response
    }
}