<?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) {
        // Apply custom CORS middleware to all API routes
        $middleware->api(prepend: [
            \App\Http\Middleware\CustomCors::class,
        ]);
        
        // Apply Sanctum stateful middleware to API routes (will be excluded for webhooks via route config)
        $middleware->statefulApi();

        $middleware->alias([
            'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
            'check.super_admin' => \App\Http\Middleware\CheckSuperAdmin::class,
            'check.module_access' => \App\Http\Middleware\CheckModuleAccess::class,
            'check.module_admin' => \App\Http\Middleware\CheckModuleAdmin::class,
            'python.api' => \App\Http\Middleware\VerifyPythonApiKey::class,
            'query.monitor' => \App\Http\Middleware\QueryMonitorMiddleware::class,
        ]);

        $middleware->validateCsrfTokens(except: [
            'api/*',
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        // Return JSON for unauthenticated API requests instead of redirecting to login
        $exceptions->respond(function (\Symfony\Component\HttpFoundation\Response $response, \Throwable $exception, \Illuminate\Http\Request $request) {
            if ($request->is('api/*')) {
                if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Unauthenticated'
                    ], 401);
                }
            }
            return $response;
        });
    })->create();
        
