package dev.ulfrx.recipe

import dev.ulfrx.recipe.auth.AuthConfig
import dev.ulfrx.recipe.auth.JwtTestSupport
import dev.ulfrx.recipe.auth.configureAuthentication
import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsText
import io.ktor.http.HttpStatusCode
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.install
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import io.ktor.server.testing.testApplication
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class ApplicationTest {
    @Test
    fun `health endpoint returns 200 with status ok`() =
        testApplication {
            // Phase 2: configureRouting now wires `meRoute` under `authenticate("authentik")`,
            // so the Authentication plugin must be installed before routing — otherwise the
            // route DSL throws MissingApplicationPluginException at registration time.
            // The verifier doesn't need to validate any tokens for this `/health` test, but
            // the plugin must exist; reuse the test JWT support to keep the wiring honest.
            val support = JwtTestSupport()
            application {
                install(ContentNegotiation) {
                    json()
                }
                configureAuthentication(
                    AuthConfig(
                        issuer = support.issuer,
                        audience = support.audience,
                        jwksUrl = "https://test-authentik.invalid/application/o/jwks/",
                    ),
                    support.provider,
                )
                configureRouting()
            }
            val response = client.get("/health")
            assertEquals(HttpStatusCode.OK, response.status)
            val body = response.bodyAsText()
            assertTrue(body.contains("\"status\""), "expected body to contain status field, was: $body")
            assertTrue(body.contains("\"ok\""), "expected body to contain ok value, was: $body")
        }
}
