<?php
/**
 * REST controller for exposing SpectatorViews data.
 *
 * @package Ilabs\Firevert\Modules\SpectatorViews\Api\Controller
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\SpectatorViews\Api\Controller;

use Ilabs\Firevert\Core\Api\Controller\AbstractController;
use Ilabs\Firevert\Modules\SpectatorViews\Api\Preparer\RenderResponsePreparer;
use Ilabs\Firevert\Modules\SpectatorViews\Services\SpectatorTrackingService;
use Ilabs\Firevert\Modules\SpectatorViews\Services\Type\ModuleType;
use WP_REST_Request;
use WP_REST_Response;
use Ilabs\Firevert\Modules\SpectatorViews\Services\Repository\SpectatorViewsRepository;

/**
 * Class RenderController
 */
final class RenderController extends AbstractController {

	/**
	 * SpectatorViewsRepository instance.
	 *
	 * @var SpectatorViewsRepository
	 */
	private SpectatorViewsRepository $repository;

	/**
	 * Constructor.
	 *
	 * @param SpectatorViewsRepository $repository The repository instance.
	 */
	public function __construct( SpectatorViewsRepository $repository ) {
		$this->repository = $repository;

		parent::__construct();
	}

	/**
	 * Registers REST API routes.
	 *
	 * @return void
	 */
	public function register_routes(): void {
		add_action( 'rest_api_init', array( $this, 'on_rest_api_init' ) );
	}

	/**
	 * Registers the actual REST API route for the SpectatorViews.
	 *
	 * @return void
	 */
	public function on_rest_api_init(): void {
		register_rest_route(
			'firevert/v1',
			'/spectator-views/main',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_main_widget_data' ),
				'permission_callback' => $this->get_permission_callback(),
			)
		);
	}

	/**
	 * Returns main SpectatorViews data as JSON.
	 *
	 * @param WP_REST_Request $request Request.
	 *
	 * @return WP_REST_Response REST response with widget data.
	 */
	public function get_main_widget_data( WP_REST_Request $request ): WP_REST_Response {
		$lang = $request->get_param( 'locale' );
		$lang = is_string( $lang ) ? $lang : null;

		$product_id = $request->get_param( 'product_id' );
		$product_id = null !== $product_id ? (int) $product_id : null;

		$post = $this->repository->get_or_create_main();
		$data = $this->repository->get_widget_data( $post, $lang );

		/**
		 * Get from container DI.
		 *
		 * @var SpectatorTrackingService $tracker
		 */
		$tracker = firevert_container()->get( 'tracking_service', ModuleType::MODULE_SLUG );

		$response_data = RenderResponsePreparer::prepare_main_response( $product_id, $post, $data, $tracker );

		return new WP_REST_Response( $response_data );
	}
}
