<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        // Alias middleware — Laravel 13 pakai alias(), bukan $routeMiddleware array
        $middleware->alias([
            'role'                 => \App\Http\Middleware\RoleMiddleware::class,
            'check.active.session' => \App\Http\Middleware\CheckActiveSession::class,
        ]);
        // Uncomment jika di belakang reverse proxy / CDN:
        // $middleware->trustProxies(at: '*');
    })
    ->withExceptions(function (Exceptions $exceptions) {
        // 404 redirect friendly
        $exceptions->render(function (NotFoundHttpException $e, Request $request) {
            if ($request->expectsJson()) {
                return response()->json(['message' => 'Resource tidak ditemukan.'], 404);
            }
            return redirect()->route('dashboard')->with('error', 'Halaman tidak ditemukan.');
        });
        // 403 Forbidden
        $exceptions->render(function (AccessDeniedHttpException $e, Request $request) {
            if ($request->expectsJson()) {
                return response()->json(['message' => 'Akses ditolak.'], 403);
            }
            return redirect()->back()->with('error', 'Anda tidak memiliki akses ke halaman tersebut.');
        });
    })->create();
