<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Services\ServerHunterService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AllowServerHunterSpider
{
    public function __construct(
        private ServerHunterService $serverHunterService,
    ) {}

    public function handle(Request $request, Closure $next): Response
    {
        $allowedIps = $this->serverHunterService->getSpiderIps();

        if (empty($allowedIps)) {
            // If we couldn't fetch the IP list, deny all to be safe
            abort(403, 'ServerHunter spider IP list unavailable.');
        }

        if (! in_array($request->ip(), $allowedIps, true)) {
            abort(403, 'Access denied.');
        }

        return $next($request);
    }
}
