import com.correx.infrastructure.compression.HttpTokenPruner
import io.ktor.client.HttpClient
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.headersOf
import io.ktor.serialization.kotlinx.json.json
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals

class HttpTokenPrunerTest {

    private fun client(engine: MockEngine) = HttpClient(engine) {
        install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) }
    }

    @Test
    fun `returns sidecar compressed output`() = runBlocking {
        val engine = MockEngine {
            respond(
                content = """{"compressed":"short text 10.0.0.1"}""",
                status = HttpStatusCode.OK,
                headers = headersOf(HttpHeaders.ContentType, "application/json"),
            )
        }
        val pruner = HttpTokenPruner(client = client(engine))
        assertEquals("short text 10.0.0.1", pruner.prune("a very long text 10.0.0.1", listOf("10.0.0.1"), 0.5))
    }

    @Test
    fun `fails open when sidecar errors`() = runBlocking {
        val engine = MockEngine { respond("boom", HttpStatusCode.InternalServerError) }
        val pruner = HttpTokenPruner(client = client(engine))
        val original = "keep this content untouched"
        assertEquals(original, pruner.prune(original, emptyList(), 0.5))
    }
}
