<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Middleware\TrustProxies;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Inertia\Inertia;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // 信任所有代理（用於反向代理環境）
        $middleware->trustProxies(at: '*');

        // Tenancy 必須最先執行，確保資料庫連線在 Session 讀取之前建立
        $middleware->web(prepend: [
            \App\Http\Middleware\UniversalTenancy::class,
        ]);
        $middleware->web(append: [
            \App\Http\Middleware\HandleInertiaRequests::class,
        ]);

        // 註冊 Spatie Permission 中間件別名
        $middleware->alias([
            'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // 處理 Spatie Permission 的 UnauthorizedException
        $exceptions->render(function (UnauthorizedException $e) {
            return Inertia::render('Error/Index', ['status' => 403])
                ->toResponse(request())
                ->setStatusCode(403);
        });

        // 處理 404 NotFoundHttpException
        $exceptions->render(function (NotFoundHttpException $e) {
            return Inertia::render('Error/Index', ['status' => 404])
                ->toResponse(request())
                ->setStatusCode(404);
        });

        // 處理其他一般的 HttpException (包含 403, 419, 429, 500, 503 等)
        $exceptions->render(function (HttpException $e) {
            $status = $e->getStatusCode();
            return Inertia::render('Error/Index', ['status' => $status])
                ->toResponse(request())
                ->setStatusCode($status);
        });
    })->create();

