package de.kif.backend.route.api

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

    post("/api/workgroups") {
        try {
            authenticate(Permission.WORK_GROUP) {
                val workGroup = call.receive<WorkGroup>()

                val id = WorkGroupRepository.create(workGroup)

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

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

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

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

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

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