<?php

use App\Http\Middleware\EnsureModuleEnabled;
use App\Http\Middleware\EnsureProfileCompleted;
use App\Http\Middleware\EnsureRole;
use App\Http\Middleware\EnsureSchoolIsActive;
use App\Http\Middleware\HandleInertiaRequests;
use App\Http\Middleware\PreventDashboardCache;
use App\Http\Middleware\SecurityHeaders;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

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: [HandleInertiaRequests::class, SecurityHeaders::class]);
        $middleware->alias([
            'school.active' => EnsureSchoolIsActive::class,
            'profile.complete' => EnsureProfileCompleted::class,
            'module' => EnsureModuleEnabled::class,
            'no.private.cache' => PreventDashboardCache::class,
            'role' => EnsureRole::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (Throwable $e, Request $request) {
            if ($request->expectsJson()) {
                $status = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : 500;

                return response()->json([
                    'success' => false,
                    'message' => $status === 500 ? 'خطای داخلی سرور' : $e->getMessage(),
                ], $status);
            }

            return null;
        });
    })
    ->create();
