<?php

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Foundation\Application;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

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([
            'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
            'block_suspended' => \App\Http\Middleware\BlockIfSuspended::class,
            'active' => \App\Http\Middleware\ActiveUser::class,
            'verified_dealer' => \App\Http\Middleware\VerifiedDealer::class,
        ]);

        $middleware->api(
            append: [
                \App\Http\Middleware\ApiUser::class,
            ]
        );
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (\Illuminate\Database\Eloquent\ModelNotFoundException $e, Request $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Record not found.',
                    'data' => []
                ], JsonResponse::HTTP_NOT_FOUND);
            }
        });

        $exceptions->render(function (AuthenticationException $e, Request $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized.',
                    'data' => []
                ], JsonResponse::HTTP_UNAUTHORIZED);
            }
        });

        $exceptions->render(function (\Exception $e, Request $request) {
            if ($request->expectsJson()) {
                $statusCode = $e->getCode();
                $statusCode = is_int($statusCode) && $statusCode > 99 ? $statusCode : 500;

                return response()->json([
                    'success' => false,
                    'message' => $e->getMessage(),
                    'data' => []
                ], $statusCode);
            }

        });
    })->create();
