<?php

namespace Limb_Chatbot\Includes\Services\Actions;

use Limb_Chatbot\Includes\Data_Objects\Action_Plan;
use Limb_Chatbot\Includes\Data_Objects\Chat;
use Limb_Chatbot\Includes\Data_Objects\Message;
use Limb_Chatbot\Includes\Utilities\Chatbot_Utility;

class Action_Executor {
	private Chat $chat;
	private Action_Submission_Message_Builder $submission_message_builder;

	public function __construct( Chat $chat, Chatbot_Utility $chatbot_utility ) {
		$this->chat                       = $chat;
		$this->submission_message_builder = new Action_Submission_Message_Builder( $chatbot_utility );
	}

	/**
	 * Execute action with collected parameters
	 *
	 * @param  Action_Plan  $action_plan  Completed action plan
	 *
	 * @return Message Result message
	 * @throws \Exception
	 * @since 1.0.0
	 */
	public function execute( Action_Plan $action_plan ): Message {
		// Execute action callbacks
		$service = new Action_Submission_Service( $action_plan->action(), $action_plan, $this->chat );
		$result  = $service->process_submission();

		// Build and return result message using the submission message builder
		$response_message = $this->submission_message_builder->build( $result, $action_plan->action() );

		// Clear action plan after execution
		$this->chat->update_meta( Chat::KEY_CURRENT_ACTION, null );

		return $response_message;
	}
}