<?php

/**
 * Signed tokens for public Block Builder Playground blueprint REST access.
 *
 * @package LolaCore\BlockBuilder\Playground
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\BlockBuilder\Playground;

use LolaCore\BlockBuilder\PostType\BlockPostType;

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

/**
 * Derives a stable, unguessable token from post id and block library version.
 */
final class BlockPlaygroundAccessToken {

	public static function forPost( int $postId ): string {
		$version = max(1, (int) get_post_meta($postId, BlockPostType::META_VERSION, true));

		return self::hash($postId, $version);
	}

	public static function verify( int $postId, string $token ): bool {
		if ($token === '') {
			return false;
		}

		return hash_equals(self::forPost($postId), $token);
	}

	private static function hash( int $postId, int $version ): string {
		return substr(
			hash_hmac('sha256', $postId . ':' . $version, wp_salt('auth')),
			0,
			32
		);
	}
}
