<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Auth\Access\AuthorizationException;
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) {
        $middleware->alias([
            'role' => App\Http\Middleware\RoleMiddleware::class,
            'attendance.access' => App\Http\Middleware\AttendanceAccessMiddleware::class,
            'attendance.users.access' => App\Http\Middleware\AttendanceUserAccessMiddleware::class,
            'warehouse.access' => App\Http\Middleware\WarehouseAccessMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (\Throwable $e, $request) {
            if ($request->expectsJson()) {
                return null;
            }

            $status = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : null;
            if ($status !== 403 && ! $e instanceof AuthorizationException) {
                return null;
            }

            $user = $request->user();
            $message = 'Anda tidak punya akses. Anda dialihkan ke halaman utama sesuai role.';

            if (! $user) {
                return redirect()->route('login')->with('error', $message);
            }

            $role = $user->role?->nama_roles;
            $route = match ($role) {
                'admin' => 'dashboard',
                'cashier' => 'dashboard.cashier',
                'supervisor' => 'orders.all',
                'waiter' => 'orders.index',
                default => 'home',
            };

            if (\Illuminate\Support\Facades\Route::has($route)) {
                return redirect()->route($route)->with('error', $message);
            }

            return redirect()->route('home')->with('error', $message);
        });
    })->create();
