<?php

namespace App\Http\Middleware;

use App\Services\BruteforceGuard;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

/**
 * Hard-blocks GUEST requests from a banned IP (403). Authenticated requests pass, so an
 * operator already logged in is never cut off mid-session and can unban their own IP from
 * the Anmeldeschutz tab. Appended to the web group so Auth::guest() resolves (the session
 * middleware has run). request()->ip() is correct via the global trustProxies (prod).
 */
class BlockBannedIp
{
    public function __construct(private BruteforceGuard $guard) {}

    public function handle(Request $request, Closure $next): Response
    {
        if ($this->guard->enabled() && Auth::guest() && $this->guard->isBanned((string) $request->ip())) {
            return response()->view('errors.blocked', [], 403);
        }

        return $next($request);
    }
}
