<?php

/**
 * Public REST endpoint that serves Playground blueprints for shareable short URLs.
 *
 * @package LolaCore\PluginBuilder\Playground
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\PluginBuilder\Playground;

if (! defined('ABSPATH')) {
	exit;
}

/**
 * GET /lolacore/v1/plugin-builder/playground-blueprint/{post_id}?token=...
 */
class PlaygroundBlueprintController {

	private const NAMESPACE = 'lolacore/v1';

	private const ROUTE = '/plugin-builder/playground-blueprint/(?P<post_id>\d+)';

	private BlueprintGenerator $blueprintGenerator;

	public function __construct( ?BlueprintGenerator $blueprintGenerator = null ) {
		$this->blueprintGenerator = $blueprintGenerator ?? new BlueprintGenerator();
	}

	public function register(): void {
		\add_action('rest_api_init', array($this, 'registerRoutes'));
	}

	public function registerRoutes(): void {
		\register_rest_route(
			self::NAMESPACE,
			self::ROUTE,
			array(
				'methods'             => 'GET',
				'callback'            => array($this, 'serveBlueprint'),
				'permission_callback' => '__return_true',
				'args'                => array(
					'post_id' => array(
						'required'          => true,
						'validate_callback' => static function ( $value ): bool {
							return is_numeric($value) && (int) $value > 0;
						},
					),
					'token'   => array(
						'required'          => true,
						'sanitize_callback' => 'sanitize_text_field',
					),
				),
			)
		);
	}

	/**
	 * @param \WP_REST_Request $request
	 * @return \WP_REST_Response|\WP_Error
	 */
	public function serveBlueprint( $request ) {
		$postId = (int) $request->get_param('post_id');
		$token  = (string) $request->get_param('token');

		if (! PlaygroundAccessToken::verify($postId, $token)) {
			return new \WP_Error(
				'lolacore_playground_forbidden',
				'Invalid or expired Playground link.',
				array('status' => 403)
			);
		}

		try {
			$payload   = $this->blueprintGenerator->loadPluginPayload($postId);
			$blueprint = $this->blueprintGenerator->buildBlueprint($payload);
		} catch (\Exception $exception) {
			return new \WP_Error(
				'lolacore_playground_blueprint_error',
				$exception->getMessage(),
				array('status' => 404)
			);
		}

		$response = new \WP_REST_Response($blueprint, 200);
		$response->header('Access-Control-Allow-Origin', '*');
		$response->header('Content-Type', 'application/json; charset=' . get_option('blog_charset', 'UTF-8'));

		return $response;
	}
}
