package de.kif.backend.route.api

import de.kif.backend.authenticate
import de.kif.backend.repository.RoomRepository
import de.kif.common.model.Permission
import de.kif.common.model.Room
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.roomApi() {
    get("/api/rooms") {
        try {
            val rooms = RoomRepository.all()
            call.success(rooms)
        } catch (_: Exception) {
            call.error(HttpStatusCode.InternalServerError)
        }
    }

    post("/api/rooms") {
        try {
            authenticate(Permission.ROOM) {
                val room = call.receive<Room>()

                val id = RoomRepository.create(room)

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

    get("/api/room/{id}") {
        try {
            val id = call.parameters["id"]?.toLongOrNull()
            val room = id?.let { RoomRepository.get(it) }

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

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

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

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