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

import com.pixelized.server.lwa.server.Engine
import com.pixelized.server.lwa.utils.extentions.exception
import com.pixelized.shared.lwa.protocol.rest.APIResponse
import com.pixelized.shared.lwa.protocol.rest.ApiPurseJson
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.putPurse(): suspend RoutingContext.() -> Unit {
    return {
        try {
            // get the query parameter
            val form = call.receive<ApiPurseJson>()
            // get the character inventory
            inventoryService.updatePurse(
                purse = form,
            )
            // send it back to the user.
            call.respond(
                message = APIResponse.success()
            )
            webSocket.emit(
                value = ApiSynchronisation.PurseUpdate(
                    timestamp = System.currentTimeMillis(),
                    characterSheetId = form.characterSheetId,
                    add = (form.gold * 10000 + form.silver * 100 + form.copper) >= 0,
                    gold = form.gold,
                    silver = form.silver,
                    copper = form.copper,
                ),
            )
        } catch (exception: Exception) {
            call.exception(
                exception = exception
            )
        }
    }
}