package de.kif.backend.route.api

import de.kif.backend.authenticate
import de.kif.backend.repository.UserRepository
import de.kif.common.model.Permission
import de.kif.common.model.User
import io.ktor.application.call
import io.ktor.http.HttpStatusCode
import io.ktor.request.receive
import io.ktor.routing.Route
import io.ktor.routing.get
import io.ktor.routing.post

fun Route.userApi() {
    get("/api/users") {
        try {
            authenticate(Permission.USER) {
                val users = UserRepository.all()
                call.success(users)
            } onFailure {
                call.error(HttpStatusCode.Unauthorized)
            }
        } catch (_: Exception) {
            call.error(HttpStatusCode.InternalServerError)
        }
    }

    post("/api/users") {
        try {
            authenticate(Permission.USER) {
                val user = call.receive<User>()

                val id = UserRepository.create(user)

                call.success(mapOf("id" to id))
            } onFailure {
                call.error(HttpStatusCode.Unauthorized)
            }
        } catch (_: Exception) {
            call.error(HttpStatusCode.InternalServerError)
        }
    }

    get("/api/user/{id}") {
        try {
            authenticate(Permission.USER) {
                val id = call.parameters["id"]?.toLongOrNull()
                val user = id?.let { UserRepository.get(it) }

                if (user != null) {
                    call.success(user)
                } else {
                    call.error(HttpStatusCode.NotFound)
                }
            } onFailure {
                call.error(HttpStatusCode.Unauthorized)
            }
        } catch (_: Exception) {
            call.error(HttpStatusCode.InternalServerError)
        }
    }

    post("/api/user/{id}") {
        try {
            authenticate {
                val id = call.parameters["id"]?.toLongOrNull()
                val user = call.receive<User>().copy(id = id)

                if (user.id != null) {
                    call.success()
                } else {
                    call.error(HttpStatusCode.NotFound)
                }
            } onFailure {
                call.error(HttpStatusCode.Unauthorized)
            }
        } catch (_: Exception) {
            call.error(HttpStatusCode.InternalServerError)
        }
    }
    post("/api/user/{id}/delete") {
        try {
            authenticate {
                val id = call.parameters["id"]?.toLongOrNull()

                if (id != null) {
                    UserRepository.delete(id)
                    call.success()
                } else {
                    call.error(HttpStatusCode.NotFound)
                }
            } onFailure {
                call.error(HttpStatusCode.Unauthorized)
            }
        } catch (_: Exception) {
            call.error(HttpStatusCode.InternalServerError)
        }
    }
}
