<?php

namespace App\Middleware;

use App\Core\Middleware\MiddlewareInterface;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;

class RateLimitMiddleware implements MiddlewareInterface
{
    private int $maxRequests = 60;
    private int $windowSeconds = 60;

    public function handle(Request $request): ?Response
    {
        $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        $key = 'rate_limit_' . md5($ip);

        if (!isset($_SESSION[$key])) {
            $_SESSION[$key] = ['count' => 0, 'start' => time()];
        }

        $data = &$_SESSION[$key];

        if (time() - $data['start'] > $this->windowSeconds) {
            $data = ['count' => 0, 'start' => time()];
        }

        $data['count']++;

        if ($data['count'] > $this->maxRequests) {
            return new Response('Too Many Requests', 429);
        }

        return null;
    }
}
