<?php

use App\Http\Middleware\CheckHasRootUser;
use App\Http\Middleware\SetLocale;
use App\Http\Middleware\UpdateLastActive;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Session\TokenMismatchException;
use Spatie\Permission\Middleware\PermissionMiddleware;
use Spatie\Permission\Middleware\RoleMiddleware;
use Spatie\Permission\Middleware\RoleOrPermissionMiddleware;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Auth\Access\AuthorizationException;


return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->redirectGuestsTo('/user/login');

        $middleware->validateCsrfTokens(except: [
            'aamarpay/payment/success',
            'aamarpay/payment/fail',
            'aamarpay/payment/cancel',
        ]);

        $middleware->appendToGroup('web', [
            SetLocale::class,
            UpdateLastActive::class,
        ]);

        $middleware->alias([
            'role' => RoleMiddleware::class,
            'permission' => PermissionMiddleware::class,
            'role_or_permission' => RoleOrPermissionMiddleware::class,
            'has_root_user' =>  CheckHasRootUser::class,
        ]);
    })
    ->withEvents(discover: [
        __DIR__ . '/../app/Listeners',
    ])
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (TokenMismatchException $e, Request $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'message' => 'Your session has expired. Please login again.',
                ], 419);
            }

            $loginRoute = $request->is('admin/*') || $request->is('login') || $request->is('logout')
                ? route('admin.login.view')
                : route('user.login');

            return redirect($loginRoute)
                ->with('error', 'Your session has expired. Please login again.');
        });

        $exceptions->render(function (AuthorizationException $e, Request $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'message' => 'You do not have permission to access this page.',
                ], 403);
            }

            $loginRoute = $request->is('admin/*') || $request->is('login') || $request->is('logout')
                ? route('admin.login.view')
                : route('user.login');

            return redirect($loginRoute)
                ->with('error', 'You do not have permission to access this page. Please login again.');
        });

        $exceptions->render(function (NotFoundHttpException $e, $request) {
            return response()->view('errors.404', [], 404);
        });

    })->create();
