package de.kif.backend.route.api

import de.kif.backend.PortalSession
import de.kif.backend.checkPassword
import de.kif.backend.repository.UserRepository
import io.ktor.application.ApplicationCall
import io.ktor.application.call
import io.ktor.http.HttpStatusCode
import io.ktor.request.receive
import io.ktor.response.respond
import io.ktor.routing.Route
import io.ktor.routing.post
import io.ktor.sessions.sessions
import io.ktor.sessions.set

data class Credentials(
    val username: String,
    val password: String
)

fun Route.authenticateApi() {
    post("/api/authenticate") {
        val credentials = call.receive<Credentials>()

        val user = UserRepository.find(credentials.username)

        if (user?.id == null || !checkPassword(credentials.password, user.password)) {
            call.error(HttpStatusCode.Unauthorized)
            return@post
        }

        call.sessions.set(PortalSession(user.id))
        call.respond(HttpStatusCode.OK, mapOf("OK" to true))
    }
}

suspend fun ApplicationCall.success(data: Any? = null) {
    val map: Map<String, Any>

    if (data == null) {
        map = mapOf("OK" to true)
    } else {
        map = mapOf(
            "OK" to true,
            "data" to data
        )
    }

    respond(HttpStatusCode.OK, map)
}

suspend fun ApplicationCall.error(code: HttpStatusCode) {
    respond(
        code,
        mapOf(
            "OK" to false,
            "errorCode" to code.value,
            "errorDescription" to code.description
        )
    )
}