package de.kif.backend.route.api

import de.kif.backend.authenticate
import de.kif.backend.repository.AnnouncementRepository
import de.kif.common.model.Permission
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.announcementApi() {
    get("/api/announcement") {
        try {
            call.success(AnnouncementRepository.getAnnouncement())
        } catch (_: Exception) {
            call.error(HttpStatusCode.InternalServerError)
        }
    }

    post("/api/announcement") {
        try {
            authenticate(Permission.POST) {
                val announcement = call.receive<String>()

                AnnouncementRepository.setAnnouncement(announcement)

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