<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use App\Support\ApiResponse;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

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) {
        // No statefulApi() — this is a token-only SPA (bearer tokens via Sanctum
        // PersonalAccessToken). Enabling stateful mode triggers CSRF (419) on
        // proxied requests from localhost:3000.
        $middleware->api(prepend: [
            \Illuminate\Http\Middleware\HandleCors::class,
        ]);
        $middleware->redirectGuestsTo(fn () => null);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (ValidationException $e) {
            return ApiResponse::error($e->getMessage(), ['errors' => $e->errors()], 422);
        });
        $exceptions->render(function (AuthenticationException $e) {
            return ApiResponse::error('Unauthenticated', null, 401);
        });
        $exceptions->render(function (NotFoundHttpException $e) {
            return ApiResponse::error('Route not found', null, 404);
        });
        $exceptions->render(function (\Throwable $e, $request) {
            if (!$request->is('api/*')) {
                return null;
            }
            $code = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : 500;
            $message = config('app.debug') ? $e->getMessage() : 'Server error';
            return ApiResponse::error($message ?: 'Server error', null, $code ?: 500);
        });
    })->create();
