<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\DocStoreBundle\Service\Cryptography;

use Base64Url\Base64Url;
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
use Random\Randomizer;

class KeyGenerator
{
    private readonly Randomizer $randomizer;

    public function __construct()
    {
        $this->randomizer = new Randomizer();
    }

    /**
     * @return array{alg: string, ext: bool, k: string, key_ops: list<string>, kty: string}
     */
    public function generateKey(string $algo = StoredObjectManagerInterface::ALGORITHM): array
    {
        if (StoredObjectManagerInterface::ALGORITHM !== $algo) {
            throw new \LogicException(sprintf("Algorithm '%s' is not supported.", $algo));
        }

        $key = $this->randomizer->getBytes(32);

        return [
            'alg' => 'A256CBC',
            'ext' => true,
            'k' => Base64Url::encode($key),
            'key_ops' => ['encrypt', 'decrypt'],
            'kty' => 'oct',
        ];
    }

    /**
     * @return list<int<0, 255>>
     */
    public function generateIv(): array
    {
        $iv = [];
        for ($i = 0; $i < 16; ++$i) {
            $iv[] = unpack('C', $this->randomizer->getBytes(8))[1];
        }

        return $iv;
    }
}
