<?php

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

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        channels: __DIR__.'/../routes/channels.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->api(prepend: [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        ]);

        $middleware->alias([
            'verified'           => \App\Http\Middleware\EnsureEmailIsVerified::class,
            'role'               => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission'         => \Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
            'set-tenant'         => \App\Http\Middleware\SetTenantScope::class,
            'set-branch'         => \App\Http\Middleware\SetBranchScope::class,
            'multi-branch'       => \App\Http\Middleware\RequiresMultiBranchFeature::class,
            'plan-feature'       => \App\Http\Middleware\CheckPlanFeature::class,
            'org-feature'        => \App\Http\Middleware\CheckOrgFeature::class,
            'requires-subscription' => \App\Http\Middleware\RequiresActiveSubscription::class,
            'platform.admin'     => \App\Http\Middleware\EnsurePlatformAdmin::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        // When MySQL is briefly unavailable (e.g. XAMPP restart), return a clean
        // 503 JSON response instead of a 500 stack trace. The frontend will show
        // a user-friendly "Service unavailable" toast rather than a raw error.
        $exceptions->render(function (\Illuminate\Database\QueryException $e, $request) {
            // HY000 [2002] = "No connection could be made / Connection refused"
            if ($e->getCode() === 2002 && $request->expectsJson()) {
                return response()->json([
                    'message' => 'Database is temporarily unavailable. Please try again in a moment.',
                ], 503);
            }
        });
    })->create();
