<?php

use App\Http\Middleware\HandleAppearance;
use App\Http\Middleware\HandleInertiaRequests;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
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) {
        $middleware->encryptCookies(except: ['appearance', 'sidebar_state']);

        $middleware->web(append: [
            HandleAppearance::class,
            HandleInertiaRequests::class,
            AddLinkHeadersForPreloadedAssets::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        if (app()->environment(['production', 'development', 'local'])) {
            $exceptions->render(function (Exception $e, Request $request) {
                $status = match (true) {
                    $e instanceof NotFoundHttpException => 404,
                    $e instanceof \Illuminate\Auth\AuthenticationException => 401,
                    $e instanceof \Illuminate\Auth\Access\AuthorizationException => 403,
                    $e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException => 405,
                    $e instanceof \Illuminate\Validation\ValidationException => 422,
                    default => 500,
                };
                if ($request->is('api/*')) {
                    return response()->json(['message' => $e->getMessage()], $status);
                }
                // else {
                //     if (Auth::check()) {
                //         return Inertia::render('dashboard_not_found', [
                //             'status' => $status,
                //             'message' => $e->getMessage(),
                //         ])->toResponse($request)->setStatusCode($status);
                //     } else {
                //         if ($status == 401) {
                //             return redirect()->guest(route('login'));
                //         } else if($status == 422){
                //             return redirect()->guest(route('login'))->withErrors(['message' => $e->getMessage()]);
                //         }
                //         return Inertia::render('not_found')->toResponse($request)->setStatusCode($status);
                //     }
                // }
            });
        }
    })->create();
