<?php

use App\Services\ApplicationUrlService;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;

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->append(\App\Http\Middleware\SecurityHeaders::class);

        $middleware->alias([
            // JWT auth
            'jwt.auth' => \PHPOpenSourceSaver\JWTAuth\Http\Middleware\Authenticate::class,
            'jwt.refresh' => \PHPOpenSourceSaver\JWTAuth\Http\Middleware\RefreshToken::class,
            'api.jwt' => \App\Http\Middleware\ApiJwtAuth::class,

            // Multi-guard auth (both the new and legacy alias point at the same class)
            'auth.multi' => \App\Http\Middleware\MultiAuth::class,
            'multi.auth' => \App\Http\Middleware\MultiAuth::class,

            // Permission / role gates
            'perm' => \App\Http\Middleware\RequirePermission::class,
            'require.permission' => \App\Http\Middleware\RequirePermission::class,
            'admin.access' => \App\Http\Middleware\EnsurePrintRequestsAdminAccess::class,
            'parent.access' => \App\Http\Middleware\EnsureParentProgressAccess::class,
            'parent.progress' => \App\Http\Middleware\EnsureParentProgressAccess::class,
            'teacher.progress' => \App\Http\Middleware\EnsureClassProgressTeacherPortalAccess::class,
            'class_progress.teacher' => \App\Http\Middleware\EnsureClassProgressTeacherPortalAccess::class,
            'school_year.editable' => \App\Http\Middleware\EnsureSchoolYearEditable::class,
            'print_requests.teacher' => \App\Http\Middleware\EnsurePrintRequestsTeacherAccess::class,
            'print_requests.admin' => \App\Http\Middleware\EnsurePrintRequestsAdminAccess::class,
            'badge_scan.logs' => \App\Http\Middleware\EnsureBadgeScanLogsAccess::class,

            // Docs + teacher portal
            'auth.docs' => \App\Http\Middleware\ApiDocsAuth::class,
            'teacher.portal.auth' => \App\Http\Middleware\TeacherPortalAuthenticate::class,

            // Utility
            'timezone' => \App\Http\Middleware\PrimeTimezone::class,
            'prime.timezone' => \App\Http\Middleware\PrimeTimezone::class,
            'cleanup.scheduler' => \App\Http\Middleware\CleanupScheduler::class,
        ]);

        $middleware->redirectGuestsTo(function (Request $request) {
            if ($request->is('api/*') || $request->expectsJson()) {
                return null;
            }

            return app(ApplicationUrlService::class)->webLoginUrl();
        });
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (AuthenticationException $e, Request $request) {
            if ($request->is('api/*') || $request->expectsJson()) {
                return response()->json(['message' => 'Unauthorized.'], 401);
            }
        });
    })->create();
