<?php

use App\Http\Middleware\BoolTransformerMiddleware;
use App\Http\Middleware\Localization;
use App\Http\Middleware\setAdminGuard;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Illuminate\Validation\ValidationException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__ . '/../routes/web.php',
        api: [__DIR__ . '/../routes/api.php', __DIR__ . '/../routes/provider.php'],
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->api(append: [
            BoolTransformerMiddleware::class,
        ]);

        $middleware->append([
            setAdminGuard::class,
            Localization::class,
        ]);
        $middleware->alias([
            'provider' => \App\Http\Middleware\CheckIsProvider::class,
            'provider.inactive' => \App\Http\Middleware\CheckProviderStatus::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (\Throwable $e, Request $request) {
            if ($request->is('api/*')) {
                if ($e instanceof ValidationException) {
                    return new JsonResponse([
                        'success' => false,
                        'errors' => $e->errors(),
                        'message' => $e->getMessage(),
                    ], $e->status);
                }
                if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
                    return new JsonResponse([
                        'success' => false,
                        'errors' => [],
                        'message' => __('messages.not_found'),
                    ], status: 404);
                }
                if ($e instanceof \Illuminate\Auth\AuthenticationException) {
                    return new JsonResponse([
                        'success' => false,
                        'errors' => [],
                        'message' => __('Unauthenticated'),
                    ], status: $e->status ?? 401);
                }
                if ($e instanceof \Illuminate\Auth\Access\AuthorizationException) {
                    return new JsonResponse([
                        'success' => false,
                        'errors' => [],
                        'message' => __('messages.forbidden'),
                    ], status: 403);
                }
                if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
                    return new JsonResponse([
                        'success' => false,
                        'errors' => [],
                        'message' => __('messages.http_not_found'),
                    ], status: 404);
                }
                if ($e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException) {
                    return new JsonResponse([
                        'success' => false,
                        'errors' => [],
                        'message' => __('messages.method_not_allowed'),
                    ], status: 405);
                }
                if ($e instanceof \Symfony\Component\HttpKernel\Exception\HttpException) {
                    return new JsonResponse([
                        'success' => false,
                        'errors' => [],
                        'message' => $e->getMessage() ?? __('messages.error'),
                    ], status: $e->getStatusCode());
                }
                if ($e instanceof \Illuminate\Database\QueryException) {
                    // Handle database query exceptions
                    Log::error("Database Query Error: " . $e->getMessage(), ['exception' => $e]);

                    return new JsonResponse([
                        'success' => false,
                        'errors' => [],
                        'message' => __('messages.database_error'),
                    ], status: 500);
                }
                // Handle other exceptions
                Log::error("API Error: " . $e->getMessage(), ['exception' => $e]);

                return new JsonResponse([
                    'success' => false,
                    'errors' => [],
                    'message' => $e->getMessage() ?? __('messages.error'),
                ], status: $e->status ?? 500); // Default to 500 for unhandled exceptions
            }
        });
    })->create();
