<?php

use App\Http\Middleware\EnsureAdminHasPermission;
use App\Http\Middleware\EnsureAdminSessionIsActive;
use App\Http\Middleware\EnforceCanonicalLocalUrl;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Session\TokenMismatchException;
use Symfony\Component\HttpFoundation\Response;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        then: function (): void {
            Illuminate\Support\Facades\Route::middleware('api')
                ->prefix(trim(config('app.route_prefix').'/api', '/'))
                ->group(base_path('routes/api.php'));
        },
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->prependToGroup('web', EnforceCanonicalLocalUrl::class);
        $middleware->redirectGuestsTo(fn () => route('admin.login'));
        $middleware->alias([
            'admin.session' => EnsureAdminSessionIsActive::class,
            'permission' => EnsureAdminHasPermission::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (TokenMismatchException $exception, Request $request) {
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => __('Your session expired. Refresh the page and try again.'),
                    'error_code' => 'SESSION_EXPIRED',
                ], 419);
            }

            return redirect()
                ->route('admin.login')
                ->with('warning', __('Your session expired. Please sign in again to continue securely.'));
        });

        $exceptions->respond(function (Response $response) {
            if ($response->getStatusCode() !== 419) {
                return $response;
            }

            if (request()->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => __('Your session expired. Refresh the page and try again.'),
                    'error_code' => 'SESSION_EXPIRED',
                ], 419);
            }

            return redirect()
                ->route('admin.login')
                ->with('warning', __('Your session expired. Please sign in again to continue securely.'));
        });
    })->create();
