<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Generator;

use Ferienpass\CoreBundle\Entity\ApiToken;

class ApiTokenGenerator
{
    public function generate(string $prefix = ApiToken::PERSONAL_ACCESS_TOKEN_PREFIX): string
    {
        $locator = $this->getRandomAlphaNumStr(24);
        $secret = $this->getRandomAlphaNumStr(64);

        return \sprintf('%s%s.%s', $prefix, $locator, $secret);
    }

    private function getRandomAlphaNumStr(int $length = 20): string
    {
        $string = '';

        while (($len = \strlen($string)) < $length) {
            /** @var int<1, max> $size */
            $size = $length - $len;

            $bytes = random_bytes($size);

            $string .= substr(
                str_replace(['/', '+', '='], '', base64_encode($bytes)),
                0,
                $size
            );
        }

        return $string;
    }
}
