package com.amz.genie.services

import okhttp3.Interceptor
import okhttp3.Response

class ExpiredRetryInterceptor(private val tokenRepo: TokenRepository,
                              private val authServices: AuthServices
) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var req = chain.request()
        var resp = chain.proceed(req)

        if (resp.code == 500) {
            val peek = resp.peekBody(1024 * 1024).string()
            val looksExpired = peek.contains("token_expired", true) ||
                    peek.contains("Signature has expired", true)

            if (looksExpired) {
                resp.close()
                val refresh = tokenRepo.getRefreshToken()
                if (!refresh.isNullOrBlank()) {
                    val r = try { authServices.refresh("Bearer $refresh").execute() } catch (_: Exception) { null }
                    val newAccess = r?.body()?.accessToken
                    if (r != null && r.isSuccessful && !newAccess.isNullOrBlank()) {
                        tokenRepo.saveAccessToken(newAccess)
                        req = req.newBuilder()
                            .header("Authorization", "Bearer $newAccess")
                            .build()
                        return chain.proceed(req) // retry sekali
                    }
                }
            }
        }

        return resp
    }
}