<?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->alias([
            'admin' => \App\Http\Middleware\AdminMiddleware::class,
        ]);
        $middleware->web(\App\Http\Middleware\CheckInstalled::class);
    })
    ->withExceptions(function (Exceptions $exceptions): void {

        // ── API security blocks → always return JSON, never plain text ────────
        // This ensures Nexus (and any client) gets a structured error response
        // for every security block, so the installer can display the exact reason.
        $exceptions->render(function (\Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException $e, \Illuminate\Http\Request $request) {
            if ($request->is('api/*') || $request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'error'   => 'BRUTE_FORCE_BLOCKED',
                    'message' => 'Too many failed activation attempts from your IP address. Installation is blocked.',
                    'hint'    => 'Your IP has been temporarily blocked after repeated failures. Wait 5 minutes and try again. If you believe this is an error, contact the software vendor.',
                ], 429);
            }
        });

        $exceptions->render(function (\Symfony\Component\HttpKernel\Exception\HttpException $e, \Illuminate\Http\Request $request) {
            if ($request->is('api/*') || $request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'error'   => 'HTTP_' . $e->getStatusCode(),
                    'message' => $e->getMessage() ?: 'An HTTP error occurred.',
                    'hint'    => 'Check the License Platform URL is correct and the server is reachable.',
                ], $e->getStatusCode());
            }
        });

        $exceptions->render(function (\Throwable $e, \Illuminate\Http\Request $request) {
            if ($request->is('api/*') || $request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'error'   => 'SERVER_ERROR',
                    'message' => 'An unexpected error occurred on the License Platform.',
                    'hint'    => 'Contact the software vendor with this timestamp: ' . now()->toIso8601String(),
                ], 500);
            }
        });

    })->create();
