<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

final class TrustedHostsFromConfig
{
    public function handle(Request $request, Closure $next)
    {
        $web   = (string) config('app.web_domain', '');
        $admin = (string) config('app.admin_domain', '');

        $hosts = array_values(array_filter([$web, $admin]));

        if ($hosts) {
            $patterns = array_map(
                fn ($h) => '^' . preg_quote($h, '/') . '$',
                $hosts
            );

            SymfonyRequest::setTrustedHosts($patterns);

            // 여기서 즉시 검증 (불일치면 400)
            $request->getHost();
        }

        return $next($request);
    }
}
