package cy.hexor.furumi.data.remote

import cy.hexor.furumi.data.remote.model.ErrorResponse
import com.squareup.moshi.Moshi
import retrofit2.Response
import javax.inject.Inject

class AuthApiErrorParser @Inject constructor(
    moshi: Moshi
) {
    private val errorAdapter = moshi.adapter(ErrorResponse::class.java)

    fun messageFrom(response: Response<*>): String {
        val code = response.code()
        val rawError = response.errorBody()?.string()

        if (rawError.isNullOrBlank()) {
            return "Server error $code"
        }

        val apiError = runCatching { errorAdapter.fromJson(rawError)?.error }
            .getOrNull()
            ?.takeIf { it.isNotBlank() }

        return apiError ?: "Server error $code: ${rawError.take(MAX_ERROR_PREVIEW_LENGTH)}"
    }

    companion object {
        private const val MAX_ERROR_PREVIEW_LENGTH = 160
    }
}
