<?php
namespace Api\Core\RateLimiter;

class InMemoryRateLimiter implements RateLimiterInterface {
    private $requests;
    private $window;
    private $state = [];

    public function __construct(int $requests = 100, int $window = 60) {
        $this->requests = $requests;
        $this->window = $window;
    }

    public function allow(string $key): bool {
        $now = time();
        if (!isset($this->state[$key])) {
            $this->state[$key] = ['tokens' => $this->requests - 1, 'last' => $now];
            return true;
        }
        $data = $this->state[$key];
        $elapsed = $now - $data['last'];
        $rate = $this->requests / $this->window;
        $refill = floor($elapsed * $rate);
        $data['tokens'] = min($this->requests, $data['tokens'] + $refill);
        $data['last'] = $now;
        if ($data['tokens'] > 0) {
            $data['tokens']--;
            $this->state[$key] = $data;
            return true;
        }
        $this->state[$key] = $data;
        return false;
    }

    public function getRetryAfter(string $key): int {
        if (!isset($this->state[$key])) return 0;
        $data = $this->state[$key];
        if ($data['tokens'] > 0) return 0;
        $elapsed = time() - $data['last'];
        return max(0, $this->window - $elapsed);
    }
}
