package com.horrortv.app.util

import android.util.Log
import com.horrortv.app.domain.model.AppError

object ErrorLogger {
    private const val TAG_PREFIX = "HorrorTV"

    fun logError(
        component: String,
        operation: String,
        error: AppError,
        additionalContext: Map<String, Any?> = emptyMap()
    ) {
        val fullTag = "$TAG_PREFIX-$component"

        val contextStr = if (additionalContext.isNotEmpty()) {
            additionalContext.entries.joinToString(", ") { "${it.key}=${it.value}" }
        } else ""

        val message = buildString {
            append("[$operation] ")
            append(error.debugMessage)
            if (contextStr.isNotEmpty()) {
                append(" | Context: $contextStr")
            }
            append(" | Retryable: ${error.isRetryable}")
        }

        when (error) {
            is AppError.NetworkError -> {
                Log.w(fullTag, message)
                error.cause?.let { Log.w(fullTag, "Cause: ${it.message}", it) }
            }
            is AppError.ApiError -> {
                val priority = if (error.code >= 500) Log.ERROR else Log.WARN
                Log.println(priority, fullTag, "$message | Status: ${error.code}")
            }
            is AppError.CacheError -> Log.e(fullTag, message)
            is AppError.ValidationError -> Log.w(fullTag, message)
            is AppError.UnknownError -> {
                Log.e(fullTag, message)
                error.cause?.let { Log.e(fullTag, "Cause: ${it.message}", it) }
            }
        }
    }

    fun logInfo(component: String, operation: String, message: String) {
        Log.i("$TAG_PREFIX-$component", "[$operation] $message")
    }

    fun logDebug(component: String, operation: String, message: String) {
        Log.d("$TAG_PREFIX-$component", "[$operation] $message")
    }

    fun logWarning(component: String, operation: String, message: String) {
        Log.w("$TAG_PREFIX-$component", "[$operation] $message")
    }
}