<?php

namespace Limb_Chatbot\Includes\Services\Actions;

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\Services\Stream_Event_Service;

/**
 * Class Email_Verification_Message_Builder
 *
 * Builds user-friendly messages requesting email verification codes.
 *
 * @package Limb_Chatbot\Includes\Services\Actions
 * @since 1.0.0
 */
class Email_Verification_Message_Builder {

	/**
	 * Build verification request message
	 *
	 * @param  Action_Plan  $action_plan  The current action plan
	 * @param  Action_Plan_Step  $step  The verification step
	 *
	 * @return Message The verification request message
	 * @since 1.0.0
	 */
	public function build( Action_Plan $action_plan, Action_Plan_Step $step, $stream = false ): Message {
		$step_data = $step->get_data();
		$email     = $step_data['email'] ?? 'your email';

		$text = sprintf(
			__( 'I\'ve sent a verification code to %s. Please enter the 6-digit code you received to verify your email address.',
				'limb-chatbot' ),
			'**' . esc_html( $email ) . '**'
		);

		if ( $stream ) {
			Stream_Event_Service::text( $text );
		}

		$parameter = $this->create_parameter();

		$content = [
			[
				'type' => Message::CONTENT_TYPE_TEXT,
				'text' => [ 'value' => $text ],
			],
			[
				'type'                          => Message::CONTENT_TYPE_PARAMETER,
				Message::CONTENT_TYPE_PARAMETER => $parameter,
			],
		];

		return Message::make( [
			'role'    => Message::ROLE_ASSISTANT,
			'content' => $content,
		] );
	}

	private function create_parameter() {
		$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 $parameter;
	}
}
