package com.tt.honeyDue.network

import com.tt.honeyDue.models.ErrorResponse
import io.ktor.client.call.body
import io.ktor.client.statement.HttpResponse
import kotlinx.serialization.json.Json

object ErrorParser {
    private val json = Json {
        ignoreUnknownKeys = true
        isLenient = true
    }

    /**
     * Parses error response from the backend.
     * The backend returns: {"error": "message"}
     * Falls back to detail field or field-specific errors if present.
     * For 429 responses, includes the Retry-After value in the message.
     */
    suspend fun parseError(response: HttpResponse): String {
        // Handle 429 rate-limit responses with Retry-After header
        if (response.status.value == 429) {
            val retryAfter = response.headers["Retry-After"]?.toLongOrNull()
            return if (retryAfter != null) {
                "Too many requests. Please try again in $retryAfter seconds."
            } else {
                "Too many requests. Please try again later."
            }
        }

        return try {
            val errorResponse = response.body<ErrorResponse>()

            // Build detailed error message
            val message = StringBuilder()

            // Primary: use the error field (main error message from backend)
            message.append(errorResponse.error)

            // Secondary: append detail if present and different from error
            errorResponse.detail?.let { detail ->
                if (detail.isNotBlank() && detail != errorResponse.error) {
                    message.append(": $detail")
                }
            }

            // Add field-specific errors if present
            errorResponse.errors?.let { fieldErrors ->
                if (fieldErrors.isNotEmpty()) {
                    message.append("\n\nDetails:")
                    fieldErrors.forEach { (field, errors) ->
                        message.append("\n• $field: ${errors.joinToString(", ")}")
                    }
                }
            }

            message.toString()
        } catch (e: Exception) {
            // Fallback: try to parse as simple {"error": "message"} map
            try {
                val simpleError = response.body<Map<String, String>>()
                simpleError["error"] ?: simpleError["message"] ?: simpleError["detail"]
                    ?: "An error occurred (${response.status.value})"
            } catch (e2: Exception) {
                // Last resort: read as plain text
                try {
                    response.body<String>()
                } catch (e3: Exception) {
                    "An error occurred (${response.status.value})"
                }
            }
        }
    }
}
