<?php

use App\Http\Middleware\EnsureActiveUser;
use App\Http\Middleware\RequireIdempotencyKey;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        apiPrefix: 'api',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->append(\App\Http\Middleware\SecurityHeaders::class);
        $middleware->alias([
            'active' => EnsureActiveUser::class,
            'idempotency.required' => RequireIdempotencyKey::class,
            'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->dontFlash(['password','password_confirmation','current_password','code','sender_id_number','recipient_id_number']);
        $exceptions->shouldRenderJsonWhen(fn (Request $request) => $request->is('api/*'));
        $exceptions->render(function (Throwable $e, Request $request) {
            if (! $request->is('api/*')) {
                return null;
            }
            if ($e instanceof \App\Domain\Transfers\Exceptions\DomainException) {
                return response()->json(['error' => ['code' => $e->errorCode, 'message' => $e->getMessage()]], $e->httpStatus);
            }
            if ($e instanceof \Illuminate\Validation\ValidationException) {
                return response()->json([
                    'error' => ['code' => 'VALIDATION_FAILED', 'message' => 'The submitted data is invalid.'],
                    'fields' => $e->errors(),
                ], 422);
            }
            if ($e instanceof \Illuminate\Auth\AuthenticationException) {
                return response()->json(['error' => ['code' => 'UNAUTHENTICATED', 'message' => 'Authentication is required.']], 401);
            }
            if ($e instanceof \Illuminate\Auth\Access\AuthorizationException) {
                return response()->json(['error' => ['code' => 'FORBIDDEN', 'message' => 'You are not allowed to perform this action.']], 403);
            }
            if ($e instanceof HttpExceptionInterface) {
                return response()->json(['error' => ['code' => 'HTTP_'.$e->getStatusCode(), 'message' => $e->getMessage() ?: 'Request failed.']], $e->getStatusCode());
            }
            report($e);
            return response()->json(['error' => ['code' => 'INTERNAL_ERROR', 'message' => $e->getMessage()]], 500);
        });
    })->create();
