<?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\Data_Objects\Parameter;
use Limb_Chatbot\Includes\Exceptions\Error_Codes;
use Limb_Chatbot\Includes\Exceptions\Exception;
use Limb_Chatbot\Includes\Factories\Parameter_Type_Factory;
use Limb_Chatbot\Includes\Services\Actions\Action_Executor;

class Post_Data_Collecting_Processor extends Data_Collecting_Processor {

	public function process( Action_Plan $action_plan, Action_Plan_Step $step, Message $user_message ): Message {
		try {
			$user_input = trim( $this->extract_parameter_value( $user_message ) );
			$step_data  = $step->get_data();
			$parameter  = $step_data['parameter'] ?? null;
			if ( ! $parameter instanceof Parameter ) {
				throw new Exception( Error_Codes::VALIDATION_INVALID_VALUE,
					__( 'Invalid parameter in post-collection step', 'limb-chatbot' ) );
			}
			// Get the parameter type handler
			$parameter_type = ( new Parameter_Type_Factory() )->make( $parameter->get_type() );
			// Let the parameter type handler process the step
			$parameter_type->process_post_collection_step( $parameter, $step_data, $user_input );
			// Mark step as complete
			$step->set_state( Action_Plan_Step::STATE_COMPLETE );
			$this->save_action_plan( $action_plan );

			// Check if there are more steps
			$next_step = $action_plan->next_incomplete_step();
			if ( $next_step ) {
				if ( $next_step->get_type() === Action_Plan_Step::TYPE_DATA_COLLECTION ) {
					return $this->parameter_message_builder->build( $action_plan, $next_step );
				}
				if ( $next_step->get_type() === Action_Plan_Step::TYPE_EMAIL_VERIFICATION ) {
					return $this->initiate_post_collection_step( $action_plan, $next_step );
				}
			}

			// All steps completed, execute action
			return ( new Action_Executor( $this->chat, $this->chatbot_utility ) )->execute( $action_plan );
		} catch ( Exception $e ) {
			return $this->get_verification_error_message( $e );
		}
	}

	private function get_verification_error_message( $e ) {
		$parameter = new Parameter();
		$parameter->set_type( Parameter::TYPE_TEXT );
		$parameter->set_name( 'email_confirmation' );
		$parameter->set_label( __( 'Email verification code', 'limb-chatbot' ) );
		$parameter->set_required( true );
		$parameter->set_placeholder( 'XXXXXX' );

		return Message::make( [
			'role'    => Message::ROLE_ASSISTANT,
			'content' => [
				[
					'type' => Message::CONTENT_TYPE_TEXT,
					'text' => [
						'value' => sprintf(
							__( 'Verification failed: %s', 'limb-chatbot' ),
							$e->getMessage()
						),
					],
				],
				[
					'type'                          => Message::CONTENT_TYPE_PARAMETER,
					Message::CONTENT_TYPE_PARAMETER => $parameter
				],
			],
		] );
	}
}