<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use App\Http\Middleware\RoleMiddleware;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\AuthenticationException;
use PHPOpenSourceSaver\JWTAuth\Exceptions\TokenExpiredException;
use PHPOpenSourceSaver\JWTAuth\Exceptions\TokenInvalidException;
use PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException;

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) {
        $middleware->alias([
            'role' => RoleMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {

        /*
        |--------------------------------------------------------------------------
        | Validation Exception Handler (422)
        |--------------------------------------------------------------------------
        */
        $exceptions->render(function (ValidationException $e, $request) {
            if ($request->expectsJson() || $request->is('api/*')) {
                $firstError = collect($e->errors())->flatten()->first();

                return response()->json([
                    'success' => false,
                    'message' => $firstError ?? 'Validation failed',
                    'data'    => null,
                    'errors'  => $e->errors(),
                ], 422);
            }
        });

        /*
        |--------------------------------------------------------------------------
        | Authentication Exception (401) → Fixes "Route [login] not defined"
        |--------------------------------------------------------------------------
        */
        $exceptions->render(function (AuthenticationException $e, $request) {
            if ($request->expectsJson() || $request->is('api/*')) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthenticated',
                    'data' => null,
                    'errors' => null,
                ], 401);
            }
        });

        /*
        |--------------------------------------------------------------------------
        | JWT Token Specific Exceptions
        |--------------------------------------------------------------------------
        */
        $exceptions->render(function (TokenExpiredException $e, $request) {
            return response()->json([
                'success' => false,
                'message' => 'Token expired',
                'data' => null,
                'errors' => null,
            ], 401);
        });

        $exceptions->render(function (TokenInvalidException $e, $request) {
            return response()->json([
                'success' => false,
                'message' => 'Token invalid',
                'data' => null,
                'errors' => null,
            ], 401);
        });

        $exceptions->render(function (JWTException $e, $request) {
            return response()->json([
                'success' => false,
                'message' => 'Token not provided',
                'data' => null,
                'errors' => null,
            ], 401);
        });

        /*
        |--------------------------------------------------------------------------
        | Global Catch-All Exception Handler (500)
        |--------------------------------------------------------------------------
        | Must be at the bottom!
        */
        $exceptions->render(function (\Throwable $e, $request) {
            if ($request->expectsJson() || $request->is('api/*')) {
                return response()->json([
                    'success' => false,
                    'message' => 'Internal Server Error',
                    'data'    => null,
                    'errors'  => [
                        'exception' => [$e->getMessage()]  // ❗ Remove in production
                    ],
                ], 500);
            }
        });

    })->create();
