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.count
import com.pixelized.server.lwa.utils.extentions.exception
import com.pixelized.server.lwa.utils.extentions.inventoryId
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.changeInventoryItemCount(): suspend RoutingContext.() -> Unit {
    return {
        try {
            // get the query parameter
            val characterSheetId = call.queryParameters.characterSheetId
            val inventoryId = call.queryParameters.inventoryId
            val count = call.queryParameters.count
            // add the item to the inventory.
            inventoryService.changeInventoryItemCount(
                characterSheetId = characterSheetId,
                inventoryId = inventoryId,
                count = count,
            )
            // API & WebSocket responses.
            call.respond(
                message = APIResponse.success(),
            )
            webSocket.emit(
                value = ApiSynchronisation.InventoryUpdate(
                    timestamp = System.currentTimeMillis(),
                    characterSheetId = characterSheetId,
                ),
            )
        } catch (exception: Exception) {
            call.exception(
                exception = exception,
            )
        }
    }
}
