<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Routing\Exceptions\InvalidSignatureException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/domains.php', //  도메인 라우팅은 routes에서 처리
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {

        // ✅ Reverse Proxy 신뢰(정확한 client ip, https 판단)
        $middleware->trustProxies(at: [
            '192.168.100.0/24',
            '127.0.0.0/8',
            '10.0.0.0/8',
            '172.16.0.0/12',
        ]);

        // ✅ trustHosts는 요청 시점에 config 기반으로 적용
        $middleware->prepend(\App\Http\Middleware\TrustedHostsFromConfig::class);

        // ✅ CSRF 예외 처리
        $middleware->validateCsrfTokens(except: [
            'auth/register/danal/result',
            'mypage/info/danal/result',
        ]);

        // ✅ alias 등록
        $middleware->alias([
            'legacy.auth'  => \App\Http\Middleware\LegacyAuth::class,
            'legacy.guest' => \App\Http\Middleware\LegacyGuest::class,
            'admin.ip'     => \App\Http\Middleware\AdminIpAllowlist::class,
            'admin.role'   => \App\Http\Middleware\AdminRole::class,
        ]);

        // ✅ guest redirect (auth 미들웨어가 login 라우트 찾다 터지는거 방지)
        $middleware->redirectGuestsTo(function (Request $request) {
            $adminHost = (string) config('app.admin_domain', '');
            return ($adminHost !== '' && $request->getHost() === $adminHost)
                ? '/login'
                : '/auth/login';
        });
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (InvalidSignatureException $e, $request) {
            return redirect('/')->with('alert', '잘못된 접근입니다.');
        });
    })
    ->create();
