<?php

use App\Enums\RoleSlug;
use App\Http\Middleware\EnsureUserHasPermission;
use App\Http\Middleware\EnsureUserHasRole;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->statefulApi();
        $middleware->alias([
            'role' => EnsureUserHasRole::class,
            'permission' => EnsureUserHasPermission::class,
        ]);
        $middleware->group('authenticated', [
            'auth:sanctum',
        ]);
        $middleware->group('admin', [
            RoleSlug::middleware(RoleSlug::Admin),
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->shouldRenderJsonWhen(
            fn (Request $request) => $request->is('api/*') || $request->expectsJson(),
        );

        $exceptions->respond(function (Response $response, Throwable $e, Request $request) {
            if (! $request->is('api/*') && ! $request->expectsJson()) {
                return $response;
            }

            $status = $response->getStatusCode();

            if ($status < 400 || $status >= 500) {
                return $response;
            }

            $payload = json_decode((string) $response->getContent(), true);

            if (! is_array($payload) || ! array_key_exists('trace', $payload)) {
                return $response;
            }

            unset($payload['exception'], $payload['file'], $payload['line'], $payload['trace']);
            $response->setContent(json_encode($payload));

            return $response;
        });
    })->create();
