<?php

namespace Limb_Chatbot\Includes\Services;

use Limb_Chatbot\Includes\Traits\SingletonTrait;
use WP_REST_Request;
use WP_REST_Server;

/**
 * Chatbot Parameter Manager
 *
 * only when needed - specifically before POST/PUT requests to settings or chatbot
 * metadata endpoints.
 *
 * This avoids initializing integration services on every plugin load.
 *
 * @package Limb_Chatbot\Includes\Services
 * @since 1.0.11
 */
class Chatbot_Parameter_Manager {

	use SingletonTrait;

	/**
	 * Whether the manager has been initialized.
	 *
	 * @var bool
	 * @since 1.0.11
	 */
	private bool $initialized = false;

	/**
	 * Routes that require parameter manager initialization.
	 *
	 * @var array
	 * @since 1.0.11
	 */
	private array $target_routes = [
//		'limb/chatbot/v1/settings',
//		'limb/chatbot/v1/chatbots',
	];

	/**
	 * Initialize the manager by registering hooks.
	 *
	 * @return void
	 * @since 1.0.11
	 */
	public function boot(): void {
		add_filter( 'rest_pre_dispatch', [ $this, 'maybe_init_services' ], 5, 3 );
	}

	/**
	 * Conditionally initialize services before handling relevant REST requests.
	 *
	 * Only initializes for POST/PUT/PATCH requests to settings or chatbot endpoints.
	 *
	 * @param mixed           $result  Response to replace the requested version with.
	 * @param WP_REST_Server  $server  Server instance.
	 * @param WP_REST_Request $request Request used to generate the response.
	 *
	 * @return mixed Unmodified result.
	 * @since 1.0.11
	 */
	public function maybe_init_services( $result, WP_REST_Server $server, WP_REST_Request $request ) {
		// Only process once
		if ( $this->initialized ) {
			return $result;
		}

		// Only for write operations (POST, PUT, PATCH)
		$method = $request->get_method();
		if ( ! in_array( $method, [ 'POST', 'PUT', 'PATCH' ], true ) ) {
			return $result;
		}

		// Check if this is a relevant route
		$route = $request->get_route();
		if ( ! $this->is_target_route( $route ) ) {
			return $result;
		}

		return $result;
	}

	/**
	 * Check if the route matches any target routes.
	 *
	 * @param string $route The current request route.
	 *
	 * @return bool True if route matches, false otherwise.
	 * @since 1.0.11
	 */
	private function is_target_route( string $route ): bool {
		foreach ( $this->target_routes as $target ) {
			if ( strpos( $route, $target ) !== false ) {
				return true;
			}
		}

		return false;
	}
}
