<?php

namespace App\Http\Middleware;

use App\Core\Request;
use App\Core\Response;
use App\Exceptions\AuthException;
use App\Infrastructure\Security\RateLimiter;

class RateLimitMiddleware
{
    public function __construct(private RateLimiter $limiter)
    {
    }

    public function handle(Request $request, callable $next): Response
    {
        $key = $request->ip() . ':' . ($request->input('email', 'anonymous'));
        if ($this->limiter->tooManyAttempts($key)) {
            throw new AuthException('Too many attempts. Please retry later.', 429);
        }

        $response = $next($request);
        $this->limiter->hit($key);
        return $response;
    }
}
