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

import com.pixelized.server.lwa.server.Engine
import com.pixelized.server.lwa.utils.extentions.create
import com.pixelized.server.lwa.utils.extentions.exception
import com.pixelized.shared.lwa.model.alteration.AlterationJson
import com.pixelized.shared.lwa.model.item.ItemJson
import com.pixelized.shared.lwa.protocol.rest.APIResponse
import com.pixelized.shared.lwa.protocol.websocket.ApiSynchronisation
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.RoutingContext

fun Engine.putItem(): suspend RoutingContext.() -> Unit {
    return {
        try {
            val form = call.receive<ItemJson>()
            val create = call.queryParameters.create

            itemService.save(
                json = form,
                create = create,
            )
            call.respond(
                message = APIResponse.success(),
            )
            webSocket.emit(
                value = ApiSynchronisation.ItemUpdate(
                    timestamp = System.currentTimeMillis(),
                    itemId = form.id,
                ),
            )
        } catch (exception: Exception) {
            call.exception(
                exception = exception,
            )
        }
    }
}