<?php

declare(strict_types=1);

namespace App\Framework\RateLimit\Storage;

use App\Framework\Cache\Cache;
use App\Framework\RateLimit\TokenBucket;

final readonly class CacheStorage implements StorageInterface
{
    public function __construct(
        private Cache $cache
    ) {}

    public function getRequestsInWindow(string $key, int $windowStart, int $windowEnd): array
    {
        $requests = $this->cache->get("rate_limit:$key:requests") ?? [];

        // Alte Requests entfernen
        $requests = array_filter($requests, fn($timestamp) => $timestamp >= $windowStart);

        // Cache aktualisieren
        $this->cache->set("rate_limit:$key:requests", $requests, 3600);

        return $requests;
    }

    public function addRequest(string $key, int $timestamp, int $ttl): void
    {
        $requests = $this->cache->get("rate_limit:$key:requests") ?? [];
        $requests[] = $timestamp;

        $this->cache->set("rate_limit:$key:requests", $requests, $ttl);
    }

    public function getTokenBucket(string $key): ?TokenBucket
    {
        $data = $this->cache->get("rate_limit:$key:bucket");

        if ($data === null) {
            return null;
        }

        return new TokenBucket(
            capacity: $data['capacity'],
            tokens: $data['tokens'],
            lastRefill: $data['last_refill']
        );
    }

    public function saveTokenBucket(string $key, TokenBucket $bucket): void
    {
        $data = [
            'capacity' => $bucket->capacity,
            'tokens' => $bucket->tokens,
            'last_refill' => $bucket->lastRefill
        ];

        $this->cache->set("rate_limit:$key:bucket", $data, 3600);
    }

    public function clear(string $key): void
    {
        $this->cache->forget("rate_limit:$key:requests");
        $this->cache->forget("rate_limit:$key:bucket");
    }
}
