package de.kif.backend.route.api

import de.kif.backend.authenticate
import de.kif.backend.repository.ScheduleRepository
import de.kif.common.checkConstraints
import de.kif.common.model.Permission
import io.ktor.application.call
import io.ktor.http.HttpStatusCode
import io.ktor.routing.Route
import io.ktor.routing.get

fun Route.constraintsApi() {
    get("/api/constraints") {
        try {
            authenticate(Permission.SCHEDULE) {
                val schedules = ScheduleRepository.all()

                val errors = checkConstraints(schedules, schedules)

                call.success(errors)
            } onFailure {
                call.error(HttpStatusCode.Unauthorized)
            }
        } catch (_: Exception) {
            call.error(HttpStatusCode.InternalServerError)
        }
    }

    get("/api/constraint/{id}") {
        try {
            authenticate(Permission.SCHEDULE) {
                val id = call.parameters["id"]?.toLongOrNull()
                val schedules = ScheduleRepository.all()

                val check = schedules.filter { it.workGroup.id == id }

                val errors = checkConstraints(check, schedules)

                call.success(errors)
            } onFailure {
                call.error(HttpStatusCode.Unauthorized)
            }
        } catch (_: Exception) {
            call.error(HttpStatusCode.InternalServerError)
        }
    }
}
