<?php

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

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        api: __DIR__.'/../routes/api.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->encryptCookies(except: ['xf_session','xf_user','xf_csrf','xf_style_variation','activity_filters']);
        $middleware->alias([
            'xf.auth' => \App\Http\Middleware\CheckXenForoPermissions::class,
            'submissions.maintenance' => \App\Http\Middleware\SubmissionsEnabled::class,
        ]);
        $middleware->redirectGuestsTo(function(Request $request): void {
            if( $request->is('manage*'))
                abort(403);
        });
        $middleware->append(\App\Http\Middleware\CheckXenForoUserState::class);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function(Throwable $e, $request) {
            $statusCode = method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500;

            if( app()->environment('production') && $statusCode >= 500 && !$request->expectsJson() ){
                $errorId = (string) Str::uuid();

                \Illuminate\Support\Facades\Log::error($e->getMessage(), [
                    'error_id' => $errorId,
                    'exception' => $e,
                    'url' => $request->fullUrl(),
                    'user_id' => (optional($request->user())->user_id ?? 0),
                ]);

                return response()->view('errors.500', ['errorId' => $errorId], 500 );
            }
        });
    })->create();
