<?php

namespace Limb_Chatbot\Includes\Services\Actions\Data_Collecting_Processors;

use Limb_Chatbot\Includes\Data_Objects\Action_Plan;
use Limb_Chatbot\Includes\Data_Objects\Action_Plan_Step;
use Limb_Chatbot\Includes\Data_Objects\Message;
use Limb_Chatbot\Includes\Services\Actions\Action_Executor;

class Standard_Data_Collecting_Processor extends Data_Collecting_Processor {

	public function process( Action_Plan $action_plan, Action_Plan_Step $step, Message $user_message ): Message {
		$user_input = trim( $this->extract_parameter_value( $user_message ) );

		// Validate, sanitize, and store the value
		$result = $this->value_processor->process( $step, $user_input );

		// If validation failed, return error message
		if ( $result->is_failed() ) {
			return $this->error_message_generator->generate( $step, $result, $this->chatbot_utility->get_stream() );
		}

		// Save updated plan with the validated value
		$this->save_action_plan( $action_plan );

		// Check if more parameters are needed
		$next_step = $action_plan->next_incomplete_step();
		if ( $next_step ) {
			// If next step is a post-collection step, handle it appropriately
			if ( $next_step->get_type() === Action_Plan_Step::TYPE_EMAIL_VERIFICATION ) {
				return $this->initiate_post_collection_step( $action_plan, $next_step );
			}

			return $this->parameter_message_builder->build( $action_plan, $next_step );
		}

		// Make sure this is needed
		$this->save_action_plan( $action_plan );

		// All parameters collected, execute the action
		return ( new Action_Executor( $this->chat, $this->chatbot_utility ) )->execute( $action_plan );
	}
}