<?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',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
         $middleware->group('api', [
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
         $exceptions->render(function (Throwable $e, $request) {

        // Only apply this to API routes
        if (! $request->is('api/*')) {
            return null; // use default for web
        }

        // Dynamic status code
        $status = 500; // default

        // Handle NOT FOUND (Model not found)
        if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
            $status = 404;
        }

        // Handle Route Not Found
        if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
            $status = 404;
        }

        // Handle Validation Errors
        if ($e instanceof \Illuminate\Validation\ValidationException) {
            $status = 422;
            return response()->json([
                'status' => false,
                'errors' => $e->errors(),
            ], $status);
        }

        // Unauthorized / Token errors
        if ($e instanceof \Illuminate\Auth\AuthenticationException) {
            $status = 401;
        }

        // Forbidden
        if ($e instanceof \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException) {
            $status = 403;
        }

        return response()->json([
            'status' => false,
            'message' => $e->getMessage(),
        ], $status);
    
    });
    })->create();
