<?php

namespace MintyPHP\Service\Security;

use MintyPHP\Cache;

class RateLimiterFallbackGateway
{
    private const KEY_PREFIX = 'rate_limit_fallback:';

    public function load(string $scope, string $subjectHash): ?array
    {
        $state = Cache::get($this->key($scope, $subjectHash));
        if (!is_array($state)) {
            return null;
        }

        return $state;
    }

    public function save(string $scope, string $subjectHash, array $state, int $ttlSeconds): bool
    {
        return Cache::set($this->key($scope, $subjectHash), $state, max(1, $ttlSeconds));
    }

    public function remove(string $scope, string $subjectHash): void
    {
        Cache::delete($this->key($scope, $subjectHash));
    }

    private function key(string $scope, string $subjectHash): string
    {
        return self::KEY_PREFIX . strtolower(trim($scope)) . ':' . trim($subjectHash);
    }
}
