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.shared.lwa.protocol.rest.APIResponse
import io.ktor.server.response.respond
import io.ktor.server.routing.RoutingContext

fun Engine.getCharacter(): suspend RoutingContext.() -> Unit {
    return {
        try {
            // get the query parameter
            val characterSheetId = call.queryParameters.characterSheetId
            // get the character sheet of the given id.
            val characterSheet = characterService
                .characterSheetJson(characterSheetId = characterSheetId)
                ?: error("CharacterSheet with id:$characterSheetId not found.")
            // send it back to the user.
            call.respond(
                message = APIResponse.success(
                    data = characterSheet,
                ),
            )
        } catch (exception: Exception) {
            call.exception(
                exception = exception
            )
        }
    }
}