<?php

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

declare(strict_types=1);

namespace LolaCore\PluginBuilder\Playground;

use LolaCore\PluginBuilder\PostType\PluginPostType;

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

/**
 * Derives a stable, unguessable token from post id and plugin version.
 */
final class PlaygroundAccessToken {

	/**
	 * Build the access token for a library entry.
	 */
	public static function forPost( int $postId ): string {
		$version = max(1, (int) get_post_meta($postId, PluginPostType::META_VERSION, true));

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

	/**
	 * Verify a token against the current library entry 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
		);
	}
}
