package com.pixelized.server.lwa.server.rest.character

import com.pixelized.server.lwa.server.Engine
import com.pixelized.server.lwa.utils.extentions.characterSheetId
import com.pixelized.server.lwa.utils.extentions.exception
import com.pixelized.server.lwa.utils.extentions.param
import com.pixelized.shared.lwa.protocol.rest.APIResponse
import com.pixelized.shared.lwa.protocol.websocket.CharacterSheetEvent
import io.ktor.server.response.respond
import io.ktor.server.routing.RoutingContext

fun Engine.putCharacterDamage(): suspend RoutingContext.() -> Unit {
    return {
        try {
            // get the query parameter
            val characterSheetId = call.queryParameters.characterSheetId
            val damage: Int = call.queryParameters.param(
                name = "damage",
                code = APIResponse.ErrorCode.Damage,
            )
            val armor: Int = call.queryParameters.param(
                name = "armor",
                code = APIResponse.ErrorCode.Armor,
            )
            // fetch the character sheet
            val characterSheet = characterService.character(characterSheetId)
                ?: error("CharacterSheet with id:$characterSheetId not found.")
            // Update the character damage
            characterService.updateDamage(
                characterSheetId = characterSheetId,
                damage = damage
            )
            // API & WebSocket responses.
            call.respond(
                message = APIResponse.success()
            )
            webSocket.emit(
                value = CharacterSheetEvent.UpdateDamage(
                    timestamp = System.currentTimeMillis(),
                    characterSheetId = characterSheetId,
                    oldValue = characterSheet.damage,
                    damage = damage,
                    armor = armor,
                )
            )
        } catch (exception: Exception) {
            call.exception(
                exception = exception
            )
        }
    }
}