<?php

namespace Limb_Chatbot\Includes\Services;

use Limb_Chatbot\Includes\Data_Objects\Parameter;
use Limb_Chatbot\Includes\Data_Objects\Widget;
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\Factories\Widget_Config_Factory;
use Limb_Chatbot\Includes\Interfaces\Widget_Callback_Interface;
use Limb_Chatbot\Includes\Repositories\Widget_Repository;
use Limb_Chatbot\Includes\Widgets\Data\Abstract_Widget_Config;
use Limb_Chatbot\Includes\Widgets\Data\Widget_Config_Interface;

/**
 * Widget domain service for config normalization and legacy migration.
 *
 * @since 2.0.0
 */
class Widget_Service {
	private Widget_Config_Factory $config_factory;

	public function __construct() {
		$this->config_factory = new Widget_Config_Factory();
	}

	public function execute_callback( Widget $widget, array $params ) {
		try {
			$config_handler = $this->config_factory->make( $widget->get_type() );
			$config_handler->set_config( $widget->get_config() );

			if ( $config_handler instanceof Widget_Callback_Interface ) {
				$params = $config_handler->sanitize_and_validate_params( $params, $config_handler );
				return $config_handler->execute_callback( $widget, $params );
			}
			throw new Exception( Error_Codes::VALIDATION_INVALID_VALUE, __( 'Invalid widget', 'limb-chatbot' ) );
		} catch ( \Exception $e ) {
			if ( $e instanceof Exception ) {
				$message = $e->getMessage();
				$code    = $e->get_error_code();
			} else {
				$message = __( 'Some error happened', 'limb-chatbot' );
				$code    = Error_Codes::TECHNICAL_ERROR;
			}

			return array(
				'success' => false,
				'code'    => $code,
				'message' => $message
			);
		}
	}
}