<?php

declare(strict_types=1);

namespace App\Framework\RateLimit;

final readonly class TokenBucket
{
    public function __construct(
        public int $capacity,
        public int $tokens,
        public int $lastRefill
    ) {
    }

    public function canConsume(int $tokens): bool
    {
        return $this->tokens >= $tokens;
    }

    public function consume(int $tokens): self
    {
        if (! $this->canConsume($tokens)) {
            throw new \InvalidArgumentException('Not enough tokens available');
        }

        return new self(
            $this->capacity,
            $this->tokens - $tokens,
            $this->lastRefill
        );
    }

    public function refill(int $tokens, int $timestamp): self
    {
        $newTokens = min($this->capacity, $this->tokens + $tokens);

        return new self(
            $this->capacity,
            $newTokens,
            $timestamp
        );
    }
}
