package com.pixelized.server.lwa.server.rest.inventory

import com.pixelized.server.lwa.server.Engine
import com.pixelized.server.lwa.utils.extentions.characterSheetId
import com.pixelized.server.lwa.utils.extentions.create
import com.pixelized.server.lwa.utils.extentions.exception
import com.pixelized.shared.lwa.model.characterSheet.CharacterSheetJson
import com.pixelized.shared.lwa.model.inventory.InventoryJson
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.putInventory(): suspend RoutingContext.() -> Unit {
    return {
        try {
            // get the query parameter
            val form = call.receive<InventoryJson>()
            val create = call.queryParameters.create
            // get the character inventory
            inventoryService.save(
                inventoryJson = form,
                create = create,
            )
            // send it back to the user.
            call.respond(
                message = APIResponse.success()
            )
            webSocket.emit(
                value = ApiSynchronisation.InventoryUpdate(
                    timestamp = System.currentTimeMillis(),
                    characterSheetId = form.characterSheetId,
                ),
            )
        } catch (exception: Exception) {
            call.exception(
                exception = exception
            )
        }
    }
}