<?php

class RateLimiter
{
    protected $redis;
    protected $limit;
    protected $window;

    public function __construct(
        \Redis $redis,
        int $limit = 100,
        int $window = 60
    ) {
        $this->redis = $redis;
        $this->limit  = $limit;
        $this->window = $window;
    }

    public function handle($request)
    {
        $ip = $request->getClientAddress();

        // Optional: include route in key
        $uri = $request->getURI();

        $key = sprintf(
            'rl:%s:%s',
            md5($uri),
            $ip
        );

        $count = $this->redis->incr($key);

        if ($count === 1) {
            $this->redis->expire(
                $key,
                $this->window
            );
        }

        if ($count > $this->limit) {
            $minutes = $this->window / 60;
            throw new CustomErrorException(BaseResponse::TOO_MANY_REQUESTS, "Terlalu banyak permintaan. Coba kembali dalam $minutes menit.");
        }
    }
}