<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        channels: __DIR__.'/../routes/channels.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // Trust all proxies (required for Herd/Valet)
        $middleware->trustProxies(at: '*');

        $middleware->web(append: [
            \App\Http\Middleware\HandleInertiaRequests::class,
            \Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
        ]);

        $middleware->alias([
            'role' => \App\Http\Middleware\EnsureRole::class,
            'subscription' => \App\Http\Middleware\EnsureActiveSubscription::class,
            'recaptcha' => \App\Http\Middleware\VerifyRecaptcha::class,
            'feature' => \App\Http\Middleware\CheckFeatureEnabled::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Handle 419 (CSRF token mismatch) - redirect back to get a fresh token
        $exceptions->renderable(function (\Illuminate\Session\TokenMismatchException $e, $request) {
            if ($request->expectsJson() || $request->header('X-Inertia')) {
                // For Inertia requests: force a full page reload to get a new CSRF token
                return redirect()->back()->with('error', 'Tu sesión expiró. Inténtalo de nuevo.');
            }
            // For normal requests: redirect back with error
            return redirect()->back()
                ->withInput($request->except('password', '_token'))
                ->with('error', 'Tu sesión expiró. Inténtalo de nuevo.');
        });
    })->create();
