<?php

use App\Exceptions\ApiException;
use App\Exceptions\BusinessException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Illuminate\Routing\Exceptions\InvalidSignatureException;

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([
            'permission' => \App\Http\Middleware\CheckPermission::class,
            'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
            'vendor' => \App\Http\Middleware\SetVendor::class,
            'vendor.access' => \App\Http\Middleware\EnsureUserVendorAccess::class,
        ]);

        // Configure rate limiting
        $middleware->api(prepend: [
            \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Helper function for JSON responses with Persian support
        $jsonResponse = fn(array $data, int $status = 200) => response()->json(
            $data, $status, [], JSON_UNESCAPED_UNICODE
        );

        // Handle API exceptions with JSON responses
        $exceptions->render(function (Throwable $e, Request $request) use ($jsonResponse) {
            if ($request->is('api/*') || $request->expectsJson()) {
                return match (true) {
                    // Business logic exceptions
                    $e instanceof BusinessException => $jsonResponse([
                        'success' => false,
                        'message' => $e->getMessage(),
                    ], $e->getCode()),

                    // Custom API exceptions
                    $e instanceof ApiException => $jsonResponse([
                        'success' => false,
                        'message' => $e->getMessage(),
                        'errors' => $e->getErrors() ?: null,
                    ], $e->getCode()),

                    // Validation errors
                    $e instanceof ValidationException => $jsonResponse([
                        'success' => false,
                        'message' => 'اطلاعات وارد شده معتبر نیست',
                        'errors' => $e->errors(),
                    ], 422),

                    // Authentication errors
                    $e instanceof AuthenticationException => $jsonResponse([
                        'success' => false,
                        'message' => 'برای دسترسی باید وارد شوید',
                    ], 401),

                    // Model not found
                    $e instanceof ModelNotFoundException => $jsonResponse([
                        'success' => false,
                        'message' => 'مورد درخواستی یافت نشد',
                    ], 404),

                    // Route not found
                    $e instanceof NotFoundHttpException => $jsonResponse([
                        'success' => false,
                        'message' => 'آدرس درخواستی یافت نشد',
                    ], 404),

                    // Named route not found (usually login route for unauthenticated API)
                    $e instanceof RouteNotFoundException => $jsonResponse([
                        'success' => false,
                        'message' => 'برای دسترسی باید وارد شوید',
                    ], 401),

                    // Invalid signature for signed URLs
                    $e instanceof InvalidSignatureException => $jsonResponse([
                        'success' => false,
                        'message' => 'لینک نامعتبر یا منقضی شده است',
                    ], 403),

                    // Forbidden (e.g. vendor access)
                    $e instanceof HttpException && $e->getStatusCode() === 403 => $jsonResponse([
                        'success' => false,
                        'message' => $e->getMessage() ?: 'دسترسی غیرمجاز',
                    ], 403),

                    // Rate limiting
                    $e instanceof TooManyRequestsHttpException => $jsonResponse([
                        'success' => false,
                        'message' => 'تعداد درخواست‌ها بیش از حد مجاز است. لطفاً کمی صبر کنید.',
                        'retry_after' => $e->getHeaders()['Retry-After'] ?? 60,
                    ], 429),

                    // Other errors - hide details in production
                    default => $jsonResponse([
                        'success' => false,
                        'message' => config('app.debug') 
                            ? $e->getMessage() 
                            : 'خطای داخلی سرور',
                        'exception' => config('app.debug') ? [
                            'type' => get_class($e),
                            'file' => $e->getFile(),
                            'line' => $e->getLine(),
                        ] : null,
                    ], 500),
                };
            }

            return null; // Let default handler handle non-API requests
        });
    })->create();
