package com.pixelized.server.lwa.server.rest.item

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

fun Engine.getItem(): suspend RoutingContext.() -> Unit {
    return {
        try {
            // get the query parameter
            val itemId = call.queryParameters.itemId
            // get the alteration of the given id.
            val item = itemService.item(itemId = itemId)
                ?: error("Item with id:$itemId not found.")
            // send it back to the user.
            call.respond(
                message = APIResponse.success(
                    data = item
                )
            )
        } catch (exception: Exception) {
            call.exception(
                exception = exception,
            )
        }
    }
}