<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class RateLimitFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $limit = isset($arguments[0]) ? max(1, (int) $arguments[0]) : 20;
        $window = isset($arguments[1]) ? max(10, (int) $arguments[1]) : 60;
        $key = 'rl_' . sha1(($request->getIPAddress() ?: 'unknown') . '|' . $request->getUri()->getPath());
        $cache = service('cache');
        $state = $cache->get($key) ?: ['count' => 0, 'reset' => time() + $window];
        if (($state['reset'] ?? 0) <= time()) $state = ['count' => 0, 'reset' => time() + $window];
        $state['count']++;
        $cache->save($key, $state, $window);
        if ($state['count'] > $limit) {
            return service('response')->setStatusCode(429)->setBody('Too many requests. Please try again shortly.');
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {}
}
