<?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',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias([
            'device.token' => \App\Http\Middleware\AuthenticateDevice::class,
            'role' => \App\Http\Middleware\EnsureUserHasRole::class,
        ]);

        // Turbify/shared-hosting install gating: every web route redirects to
        // /install until storage/app/installed.lock exists (or APP_ENV=testing);
        // every API route returns a clean JSON 503 instead of a 500/redirect.
        // See app/Http/Middleware/EnsureInstalled.php and README-DEPLOY-TURBIFY.md.
        $middleware->web(append: [\App\Http\Middleware\EnsureInstalled::class]);
        $middleware->api(append: [\App\Http\Middleware\EnsureApiInstalled::class]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->shouldRenderJsonWhen(
            fn (Request $request) => $request->is('api/*'),
        );

        $exceptions->render(function (\Illuminate\Validation\ValidationException $e, Request $request) {
            if ($request->is('api/*')) {
                return response()->json([
                    'error' => ['code' => 'validation_error', 'message' => $e->getMessage()],
                ], 422);
            }
        });

        $exceptions->render(function (\Illuminate\Auth\AuthenticationException $e, Request $request) {
            if ($request->is('api/*')) {
                return response()->json([
                    'error' => ['code' => 'unauthenticated', 'message' => 'Unauthenticated.'],
                ], 401);
            }
        });

        $exceptions->render(function (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e, Request $request) {
            if ($request->is('api/*')) {
                return response()->json([
                    'error' => ['code' => 'not_found', 'message' => 'Resource not found.'],
                ], 404);
            }
        });

        $exceptions->render(function (\Throwable $e, Request $request) {
            if ($request->is('api/*') && ! ($e instanceof \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface && $e->getStatusCode() < 500)) {
                return response()->json([
                    'error' => ['code' => 'server_error', 'message' => 'An unexpected error occurred.'],
                ], 500);
            }
        });
    })->create();
