<?php

namespace App\Filters;

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

class ApiRateLimitFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $throttler = service('throttler');
        $response = Services::response();

        $maxRequests = isset($arguments[0]) ? max(1, (int) $arguments[0]) : 60;
        $windowSeconds = isset($arguments[1]) ? max(1, (int) $arguments[1]) : MINUTE;

        $userId = session()->get('user_id');
        $identifier = $userId ? 'user:' . $userId : 'ip:' . $request->getIPAddress();
        $route = trim($request->getUri()->getPath(), '/');
        $key = 'api-rate-' . sha1($request->getMethod() . '|' . $route . '|' . $identifier);

        if (! $throttler->check($key, $maxRequests, $windowSeconds)) {
            return $response
                ->setStatusCode(429)
                ->setHeader('Retry-After', (string) $windowSeconds)
                ->setJSON([
                    'status' => false,
                    'message' => 'Too many requests. Please try again later.',
                ]);
        }

        return null;
    }

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