<?php
declare(strict_types=1);

namespace App\Middleware;

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

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

    public function handle(Request $request, callable $next): Response
    {
        $ip = $request->ip();
        $key = 'rate_limit_' . md5($ip . $request->path());

        $session = App::getInstance()->session();
        $data = $session->get($key, ['count' => 0, 'reset_at' => time() + $this->windowSeconds]);

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

        $data['count']++;
        $session->set($key, $data);

        if ($data['count'] > $this->maxRequests) {
            if ($request->isAjax() || $request->isJson()) {
                return (new Response())->json(['error' => 'تم تجاوز الحد الأقصى للطلبات. حاول لاحقاً.'], 429);
            }
            return (new Response())->html(
                '<html dir="rtl" lang="ar"><head><meta charset="utf-8"><title>كثرة الطلبات</title>'
                . '<style>body{font-family:Cairo,sans-serif;text-align:center;padding:80px;}</style></head>'
                . '<body><h1>429</h1><p>تم تجاوز الحد الأقصى للطلبات. يرجى المحاولة لاحقاً.</p></body></html>',
                429
            );
        }

        return $next($request);
    }
}