<?php
/**
 * Public reference code and secret access token for a withdrawal request.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Core;

/**
 * The reference is public and appears in emails and exports. The token is
 * secret, sent once, and stored hashed.
 */
final class ReferenceToken
{
    public const PREFIX = 'RC';

    /**
     * Derived from the record id, so uniqueness needs no counter.
     */
    public static function reference(int $year, int $id): string
    {
        return self::PREFIX . '-' . $year . '-' . $id;
    }

    public static function generate(): string
    {
        return bin2hex(random_bytes(32));
    }

    public static function hash(string $token): string
    {
        return hash('sha256', $token);
    }

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

        return hash_equals($hash, self::hash($token));
    }
}
