package de.kif.backend.route.api

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

    post("/api/tracks") {
        try {
            authenticate(Permission.WORK_GROUP) {
                val track = call.receive<Track>()

                val id = TrackRepository.create(track)

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

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

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

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

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

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