<?php
/**
 * Route handler for resolving payload variables.
 *
 * @package    100Prints
 */

class Hundred_Prints_Route_Resolve {

	/**
	 * Register routes.
	 */
	public function register_routes() {
		register_rest_route( '100prints/v1', '/resolve-payload', [
			[
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => [ $this, 'resolve_payload' ],
				'permission_callback' => [ $this, 'permission_check' ],
			],
		] );
	}

	/**
	 * Permission check callback.
	 */
	public function permission_check( $request ) {
		$params  = $request->get_json_params();
		$post_id = isset( $params['postId'] ) ? absint( $params['postId'] ) : 0;

		if ( ! $post_id ) {
			// No specific post context — require at least edit_posts capability.
			return current_user_can( 'edit_posts' );
		}

		return current_user_can( 'edit_post', $post_id );
	}

	/**
	 * Resolve variables map to final values.
	 */
	public function resolve_payload( $request ) {
		$params = $request->get_json_params();
		$variable_map = isset( $params['variableMap'] ) ? $params['variableMap'] : [];
		$post_id = isset( $params['postId'] ) ? absint( $params['postId'] ) : 0;

		$sanitized_map = hundred_prints_validate_variable_map( $variable_map );
		
		$resolver = new Hundred_Prints_Payload_Resolver();
		$payload = $resolver->resolve( $sanitized_map, $post_id );

		return rest_ensure_response( [ 'payload' => $payload ] );
	}
}
