<?php

declare(strict_types=1);

namespace App\Framework\Security\RequestSigning;

/**
 * In-memory implementation of signing key repository for development/testing
 */
final class InMemorySigningKeyRepository implements SigningKeyRepository
{
    /** @var array<string, SigningKey> */
    private array $keys = [];

    public function findByKeyId(string $keyId): ?SigningKey
    {
        return $this->keys[$keyId] ?? null;
    }

    public function store(SigningKey $key): void
    {
        $this->keys[$key->keyId] = $key;
    }

    public function remove(string $keyId): void
    {
        unset($this->keys[$keyId]);
    }

    public function getAllActive(): array
    {
        return array_filter(
            $this->keys,
            fn (SigningKey $key) => $key->isValid()
        );
    }

    public function rotateKey(string $keyId, SigningKey $newKey): void
    {
        if (isset($this->keys[$keyId])) {
            $this->remove($keyId);
        }
        $this->store($newKey);
    }

    /**
     * Add a default key for testing purposes
     */
    public function addDefaultTestKey(): SigningKey
    {
        $key = SigningKey::generateHmac(
            keyId: 'test-key-1',
            algorithm: SigningAlgorithm::HMAC_SHA256
        );

        $this->store($key);

        return $key;
    }
}
