package de.krisenvorrat.server.plugins

import de.krisenvorrat.server.model.ErrorResponse
import de.krisenvorrat.server.security.JwtService
import de.krisenvorrat.server.security.UserPrincipal
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.response.*

internal fun Application.configureAuthentication(jwtService: JwtService = JwtService(environment.config)) {
    install(Authentication) {
        jwt("auth-jwt") {
            verifier(jwtService.verifier)
            validate { credential ->
                val userId = credential.payload.getClaim("userId").asString()
                val username = credential.payload.getClaim("username").asString()
                val type = credential.payload.getClaim("type").asString()
                if (userId != null && username != null && type == "access") {
                    UserPrincipal(
                        userId = userId,
                        username = username,
                        isAdmin = credential.payload.getClaim("isAdmin").asBoolean() ?: false
                    )
                } else null
            }
            challenge { _, _ ->
                call.respond(
                    HttpStatusCode.Unauthorized,
                    ErrorResponse(status = HttpStatusCode.Unauthorized.value, message = "Missing or invalid token")
                )
            }
        }
    }
}
