<?php

use App\Http\Middleware\EnsureAdmin;
use App\Http\Middleware\EnsureApplicationIsInstalled;
use App\Http\Middleware\EnsureStaff;
use App\Http\Middleware\SetUserLocale;
use App\Infrastructure\Database\TransientConnectionHandler;
use Illuminate\Auth\Middleware\Authenticate;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        then: function () {
            Route::middleware('web')->group(base_path('routes/install.php'));

            // Nessun gruppo "web": gli endpoint di federazione sono stateless
            // (niente sessione, niente CSRF) e vengono consumati da altri
            // server, non da browser.
            Route::group([], base_path('routes/activitypub.php'));

            Route::group([], base_path('routes/cron.php'));
        },
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [
            EnsureApplicationIsInstalled::class,
            SetUserLocale::class,
        ]);

        $middleware->alias([
            'staff' => EnsureStaff::class,
            'admin' => EnsureAdmin::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (Throwable $e, Request $request) {
            $handler = app(TransientConnectionHandler::class);

            if (! $handler->isTransient($e) || $request->expectsJson()) {
                return null;
            }

            return $handler->handle($request);
        });
    })->create();

Authenticate::redirectUsing(fn () => route('login'));
