package dev.ulfrx.recipe.auth

import io.ktor.http.HttpStatusCode
import io.ktor.server.auth.authenticate
import io.ktor.server.auth.jwt.JWTPrincipal
import io.ktor.server.auth.principal
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.get

/**
 * Protected `GET /api/v1/me` route per D-27.
 *
 * The `authenticate("authentik")` block must be installed by [configureAuthentication]
 * before this route is registered. JIT user provisioning happens inside [PrincipalResolver]
 * on every authenticated call so claim drift propagates without an explicit migration.
 */
public fun Route.meRoute(principalResolver: PrincipalResolver) {
    authenticate("authentik") {
        get("/api/v1/me") {
            val jwt =
                call.principal<JWTPrincipal>()
                    ?: return@get call.respond(HttpStatusCode.Unauthorized)
            val me = principalResolver.resolve(jwt)
            call.respond(me)
        }
    }
}
