<?php

use App\Http\Middleware\EnsureAdminRole;
use App\Http\Middleware\EnsureUserIsActive;
use App\Http\Middleware\RedirectIfAuthenticated;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {

        // Redirect unauthenticated users ke admin login
        $middleware->redirectGuestsTo(fn () => route('admin.login'));

        $middleware->alias([
            // Guest = redirect jika sudah login
            'guest'  => RedirectIfAuthenticated::class,

            // Cek user aktif
            'active' => EnsureUserIsActive::class,

            // Cek role admin — menggunakan hasAnyRole() langsung, tidak lewat Gate
            // Ini menggantikan 'role:' Spatie untuk route panel admin
            'admin.role' => EnsureAdminRole::class,

            // Spatie middleware tetap tersedia untuk @can/@cannot di view
            'role'               => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission'         => \Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (\Illuminate\Auth\Access\AuthorizationException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json(['message' => 'Forbidden'], 403);
            }
            return response()->view('errors.403', [], 403);
        });

        $exceptions->render(function (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json(['message' => 'Not Found'], 404);
            }
            return response()->view('errors.404', [], 404);
        });

        // Tangkap Spatie UnauthorizedException (berbeda dari AuthorizationException)
        $exceptions->render(function (\Spatie\Permission\Exceptions\UnauthorizedException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json(['message' => 'Forbidden'], 403);
            }
            return response()->view('errors.403', [], 403);
        });
    })
    ->create();
