package com.amz.genie.services

import okhttp3.Authenticator
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route

class TokenAuthenticator(
    private val tokenRepo: TokenRepository,
    private val authApi: AuthServices
) : Authenticator {

    override fun authenticate(route: Route?, response: Response): Request? {
        // Hindari loop tak berujung
        if (responseCount(response) >= 2) return null

        val refresh = tokenRepo.getRefreshToken() ?: return null

        val refreshResp = try {
            authApi.refresh("Bearer $refresh").execute()
        } catch (_: Exception) { return null }

        if (!refreshResp.isSuccessful) return null
        val newAccess = refreshResp.body()?.accessToken ?: return null

        tokenRepo.saveAccessToken(newAccess)

        return response.request.newBuilder()
            .header("Authorization", "Bearer $newAccess")
            .build()
    }

    private fun responseCount(response: Response): Int {
        var r = response; var count = 1
        while (r.priorResponse != null) { r = r.priorResponse!!; count++ }
        return count
    }
}