<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\View;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        // Passing `using` hands Laravel full control of route registration —
        // the `web:`/`health:` convenience parameters are silently ignored
        // when it's set. So: wrap every route file in the `web` middleware
        // group ourselves (session, cookies, CSRF — `web:` alone only
        // applies that to *its own* file, not to admin.php/auth.php), and
        // re-register the /up health check the framework would have added.
        using: function (): void {
            Route::middleware('web')->group(__DIR__.'/../routes/web.php');
            Route::middleware('web')->group(__DIR__.'/../routes/admin.php');
            Route::middleware('web')->group(__DIR__.'/../routes/auth.php');

            Route::get('/up', function () {
                $exception = null;

                try {
                    Event::dispatch(new DiagnosingHealth);
                } catch (\Throwable $e) {
                    if (app()->hasDebugModeEnabled()) {
                        throw $e;
                    }

                    report($e);
                    $exception = $e->getMessage();
                }

                return response(
                    View::file(base_path('vendor/laravel/framework/src/Illuminate/Foundation/resources/health-up.blade.php'), [
                        'exception' => $exception,
                    ]),
                    status: $exception ? 500 : 200
                );
            });
        },
        commands: __DIR__.'/../routes/console.php',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'is-admin' => \App\Http\Middleware\EnsureUserIsAdmin::class,
        ]);

        // An unauthenticated visit to an /admin/* route should land on the
        // admin login screen, not the customer one.
        $middleware->redirectGuestsTo(
            fn ($request) => $request->is('admin*') ? route('admin.login') : route('login')
        );

        // Baseline security headers on every response (Step 16).
        $middleware->append(\App\Http\Middleware\SecurityHeaders::class);

        // Empty by default so local dev is unaffected — set TRUSTED_PROXIES
        // in production when running behind a load balancer/reverse proxy,
        // otherwise Request::isSecure() and the client IP will be wrong.
        $middleware->trustProxies(
            at: env('TRUSTED_PROXIES') ? explode(',', env('TRUSTED_PROXIES')) : [],
        );
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
