#include "application/config/ConfigCommandProcessor.h"

#include <utility>

#include "foundation/diagnostics/ExecutionPath.h"
#include "foundation/diagnostics/Logger.h"

namespace ta::application::config
{
    void ConfigCommandProcessor::apply(ta::ui::ConfigCommand command) const
    {
        diagnostics_.mark_command_consumed();
        if (command.type == ta::ui::ConfigCommandType::InvokeAction)
        {
            ta::application::UiAction* action = registry_.find_action(command.key);
            if (!action)
            {
                ta::foundation::execution_path::fail(command.trace_id, "ConfigCommandProcessor", "UI action key not found");
                return;
            }
            ta::foundation::execution_path::ScopedContext trace_context(command.trace_id);
            if (!actions_.dispatch(action->key(), {command.trace_id}))
                ta::foundation::execution_path::fail(command.trace_id, "ConfigCommandProcessor", "UI action handler not bound");
            return;
        }

        ConfigValue* value = registry_.find_value(command.key);
        if (!value)
        {
            ta::foundation::logger::warn("CONFIG", "command rejected | key=" + command.key + " | error=missing_key");
            return;
        }

        const ApplyResult result = value->apply(command.value);
        if (!result)
        {
            ta::foundation::logger::warn(
                "CONFIG",
                "command rejected | key=" + command.key + " | error=" + std::string(to_string(result.error)));
        }
    }
}
