<?php

namespace classes;

use interfaces\ratelimit_i;
use objects\ratelimit_o;

class ratelimit implements ratelimit_i
{
    private int $limit; // The number of requests allowed in the time period
    private int $time; // The time period in seconds

    public function __construct(int $defaultLimit, int $defaultTime)
    {
        $this->limit = $defaultLimit;
        $this->time = $defaultTime;
    }

    public function enforceIP(string $ip): bool
    {
        global $response;
        $ratelimit = (new ratelimit_o())->getOrCreateRateLimitByIp($ip);
        if ($ratelimit->count->value() >= $this->limit) {
            $response->rate_limit_exceeded();
        }
        $ratelimit->increment($ratelimit->id, 1);
        return true;
    }
}