package com.pixelized.server.lwa.server.rest.alteration

import com.pixelized.server.lwa.server.Engine
import com.pixelized.server.lwa.utils.extentions.alterationId
import com.pixelized.server.lwa.utils.extentions.exception
import com.pixelized.shared.lwa.protocol.rest.APIResponse
import com.pixelized.shared.lwa.protocol.websocket.ApiSynchronisation
import io.ktor.server.response.respond
import io.ktor.server.routing.RoutingContext

fun Engine.deleteAlteration(): suspend RoutingContext.() -> Unit {
    return {
        try {
            // get the query parameter
            val alterationId = call.parameters.alterationId
            // delete the alteration.
            alterationService.delete(
                alterationId = alterationId
            )
            // API & WebSocket responses.
            call.respond(
                message = APIResponse.success(),
            )
            webSocket.emit(
                value = ApiSynchronisation.AlterationDelete(
                    timestamp = System.currentTimeMillis(),
                    alterationId = alterationId,
                ),
            )
        } catch (exception: Exception) {
            call.exception(
                exception = exception,
            )
        }
    }
}
