<?php

declare(strict_types=1);

namespace ImovelZapAi\SuperAdmin\Infrastructure\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use ImovelZapAi\SuperAdmin\Application\Services\PlatformSettingsStore;
use Symfony\Component\HttpFoundation\Response;

final class EnsurePlatformIpAllowlist
{
    public function __construct(
        private readonly PlatformSettingsStore $settings,
    ) {}

    public function handle(Request $request, Closure $next): Response
    {
        $allowlist = $this->settings->ipAllowlist();
        $envList = array_values(array_filter(array_map('trim', explode(',', (string) config('superadmin.ip_allowlist', '')))));
        $merged = array_values(array_unique([...$allowlist, ...$envList]));

        if ($merged === []) {
            return $next($request);
        }

        $ip = (string) $request->ip();
        if (! in_array($ip, $merged, true)) {
            abort(403, 'IP não autorizado para o painel da plataforma.');
        }

        return $next($request);
    }
}
