<?php

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

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        api: __DIR__ . '/../routes/api.php',
        apiPrefix: 'api',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        // Sanctum stateful domains for SPA
        $middleware->statefulApi();

        // CORS — allow the React frontend origin
        $middleware->append(\Illuminate\Http\Middleware\HandleCors::class);

        // Alias custom middleware
        $middleware->alias([
            'tenant'        => \App\Http\Middleware\TenantMiddleware::class,
            'subscription'  => \App\Http\Middleware\SubscriptionMiddleware::class,
            'device.session'=> \App\Http\Middleware\DeviceSessionMiddleware::class,
            'api.key'       => \App\Http\Middleware\ApiKeyMiddleware::class,
            'role'          => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission'    => \Spatie\Permission\Middleware\PermissionMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        // Return JSON for all API exceptions
        $exceptions->shouldRenderJsonWhen(fn (Request $request) => $request->is('api/*'));

        // 404 — clean JSON
        $exceptions->render(function (NotFoundHttpException $e, Request $request) {
            if ($request->is('api/*')) {
                return response()->json(['error' => 'Resource not found.'], 404);
            }
        });

        // Validation errors → 422 JSON (Laravel does this by default for API routes)
        // Unauthenticated → 401
        $exceptions->render(function (\Illuminate\Auth\AuthenticationException $e, Request $request) {
            if ($request->is('api/*')) {
                return response()->json(['error' => 'Unauthenticated.'], 401);
            }
        });
    })
    ->create();
