package com.pixelized.server.lwa.server.rest.item

import com.pixelized.server.lwa.server.Engine
import com.pixelized.server.lwa.utils.extentions.exception
import com.pixelized.server.lwa.utils.extentions.itemId
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.deleteItem(): suspend RoutingContext.() -> Unit {
    return {
        try {
            // get the query parameter
            val itemId = call.queryParameters.itemId
            // delete the alteration.
            itemService.delete(
                itemId = itemId
            )
            // API & WebSocket responses.
            call.respond(
                message = APIResponse.success(),
            )
            webSocket.emit(
                value = ApiSynchronisation.ItemDelete(
                    timestamp = System.currentTimeMillis(),
                    itemId = itemId,
                ),
            )
        } catch (exception: Exception) {
            call.exception(
                exception = exception,
            )
        }
    }
}
