<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Core\MiddlewareInterface;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Services\RateLimiter;

/**
 * RateLimitMiddleware
 *
 * Usage: middleware: ['throttle:strict'] or ['throttle'] (uses the
 * 'default' limiter from config/security.php). Keys the limiter by
 * client IP; swap to Auth::id() ?? ip() if you want per-user limits on
 * authenticated routes instead.
 */
final class RateLimitMiddleware implements MiddlewareInterface
{
    public function __construct(private readonly ?string $limiterName)
    {
    }

    public function handle(Request $request, callable $next): Response
    {
        $name = $this->limiterName ?? 'default';
        $limits = config("security.rate_limits.{$name}") ?? config('security.rate_limits.default');

        $key = "throttle:{$name}:" . $request->ip();

        if (RateLimiter::tooManyAttempts($key, $limits['max_attempts'], $limits['decay_minutes'])) {
            if ($request->isAjax() || $request->isJson()) {
                return AjaxResponse::tooManyRequests();
            }

            return Response::html('429 — Too many requests. Please slow down.', 429);
        }

        RateLimiter::hit($key);

        return $next($request);
    }
}
