<?php

use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web:      __DIR__.'/../routes/web.php',
        api:      __DIR__.'/../routes/api.php',
        channels: __DIR__.'/../routes/channels.php',
        commands: __DIR__.'/../routes/console.php',
        health:   '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // Trust reverse-proxy headers so HTTPS is detected behind Nginx TLS termination
        $middleware->trustProxies(at: '*');

        // Append Sanctum SPA cookie auth to the default web group (not needed for bearer-only,
        // but harmless and enables future stateful SPA support)
        $middleware->api(append: [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        ]);

        // Rate-limit the API: 120 req/min per IP
        $middleware->throttleApi(120, 1);

        // Custom alias for role checking
        $middleware->alias([
            'operator' => \App\Http\Middleware\EnsureIsOperator::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Always return JSON for any request under /api/*
        $exceptions->shouldRenderJsonWhen(
            fn (Request $request) => $request->is('api/*'),
        );

        // Prevent the "Route [login] not defined" crash on unauthenticated API requests.
        // Laravel's Authenticate middleware normally tries to redirect to named route 'login',
        // which doesn't exist in a pure API app. Return 401 JSON instead.
        $exceptions->render(function (AuthenticationException $e, Request $request) {
            if ($request->is('api/*') || $request->expectsJson()) {
                return response()->json(['message' => 'Unauthenticated.'], 401);
            }
        });
    })->create();
