<?php

use App\Http\Middleware\AddSecurityHeaders;
use App\Http\Middleware\EnsureActiveSubscription;
use App\Http\Middleware\EnsureBusinessAccess;
use App\Http\Middleware\EnsurePlanFeature;
use App\Http\Middleware\EnsureTenantRouteModelsBelongToBusiness;
use App\Http\Middleware\EnsureUserHasRole;
use App\Http\Middleware\ResolveActiveLanguage;
use App\Http\Middleware\ResolveCurrentBusiness;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->web(append: [
            ResolveActiveLanguage::class,
            AddSecurityHeaders::class,
        ]);

        $middleware->redirectGuestsTo('/login');
        $middleware->redirectUsersTo(function (Request $request): string {
            return match ($request->user()?->role) {
                'super_admin' => '/super-admin/dashboard',
                default => '/dashboard',
            };
        });

        $middleware->alias([
            'business.access' => EnsureBusinessAccess::class,
            'subscription.active' => EnsureActiveSubscription::class,
            'subscription.feature' => EnsurePlanFeature::class,
            'tenant.model' => EnsureTenantRouteModelsBelongToBusiness::class,
            'role' => EnsureUserHasRole::class,
            'tenant' => ResolveCurrentBusiness::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
