<?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->web(append: [
            \App\Http\Middleware\HandleInertiaRequests::class,
        ]);
        
        $middleware->alias([
            'admin' => \App\Http\Middleware\AdminOnly::class,
            'landlord' => \App\Http\Middleware\LandlordOnly::class,
            'tenant' => \App\Http\Middleware\TenantOnly::class,
            'api.key' => \App\Http\Middleware\ApiKeyMiddleware::class,
        ]);

        // Redirect unauthenticated users to home (login page)
        $middleware->redirectGuestsTo(fn () => route('home'));
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Handle validation exceptions for API routes
        $exceptions->render(function (\Illuminate\Validation\ValidationException $e, $request) {
            if ($request->is('api/*')) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $e->errors(),
                ], 422);
            }
        });

        // Handle 404 and other HTTP exceptions for Inertia
        $exceptions->render(function (\Symfony\Component\HttpKernel\Exception\HttpException $e, $request) {
            if ($request->inertia() && !$request->is('api/*')) {
                $status = $e->getStatusCode();
                
                // For 404, 403, 500, etc., render Inertia error page
                if (in_array($status, [404, 403, 500, 503])) {
                    return \Inertia\Inertia::render('Admin/Error', [
                        'status' => $status,
                        'message' => match($status) {
                            404 => 'Page Not Found',
                            403 => 'Forbidden',
                            500 => 'Server Error',
                            503 => 'Service Unavailable',
                            default => 'An error occurred'
                        }
                    ])->toResponse($request)->setStatusCode($status);
                }
            }
        });
    })->create();
