<?php

use App\Http\Middleware\OrganizerApproved;
use App\Services\AuditLogger;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(\App\Http\Middleware\SanitizeInput::class);

        $middleware->alias([
            'organizer.approved' => OrganizerApproved::class,
        ]);

        $middleware->validateCsrfTokens(except: [
            'webhooks/*',
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        /*
         * Auditoría de excepciones: complementa storage/logs para reconstruir incidentes (500, errores de negocio).
         * Se omiten errores HTTP “esperados” (404, 419, validación) para no llenar la tabla.
         */
        $exceptions->report(function (\Throwable $e): void {
            if (app()->environment('testing')) {
                return;
            }
            if ($e instanceof ValidationException
                || $e instanceof AuthenticationException
                || $e instanceof NotFoundHttpException
                || $e instanceof ModelNotFoundException
                || $e instanceof TokenMismatchException) {
                return;
            }
            if ($e instanceof HttpExceptionInterface && $e->getStatusCode() < 500) {
                return;
            }

            try {
                app(AuditLogger::class)->recordException($e);
            } catch (\Throwable) {
                //
            }
        });
    })->create();
