package de.krisenvorrat.server.routes

import de.krisenvorrat.server.model.ErrorResponse
import de.krisenvorrat.server.repository.UserRepository
import de.krisenvorrat.server.security.UserPrincipal
import de.krisenvorrat.shared.model.UserListItemDto
import io.ktor.http.*
import io.ktor.server.auth.*
import io.ktor.server.response.*
import io.ktor.server.routing.*

internal fun Route.userRoutes(userRepository: UserRepository) {
    get("/api/users") {
        val principal = call.principal<UserPrincipal>()
            ?: return@get call.respond(
                HttpStatusCode.Unauthorized,
                ErrorResponse(status = 401, message = "Unauthorized")
            )
        val users = userRepository.listAll()
            .filter { it.id != principal.userId }
            .map { UserListItemDto(id = it.id, username = it.username) }
        call.respond(HttpStatusCode.OK, users)
    }
}
