<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use ImovelZapAi\Authentication\Infrastructure\Http\Middleware\EnsureRole;
use ImovelZapAi\Authentication\Infrastructure\Http\Middleware\RedirectIfEmailUnverified;
use ImovelZapAi\SuperAdmin\Infrastructure\Http\Middleware\EnsurePlatformAuthenticated;
use ImovelZapAi\SuperAdmin\Infrastructure\Http\Middleware\EnsurePlatformIpAllowlist;
use ImovelZapAi\SuperAdmin\Infrastructure\Http\Middleware\EnsurePlatformMfa;
use ImovelZapAi\SuperAdmin\Infrastructure\Http\Middleware\EnsurePlatformRole;
use ImovelZapAi\Tenancy\Infrastructure\Http\Middleware\EnsureTenantContext;
use ImovelZapAi\Tenancy\Infrastructure\Http\Middleware\EnsureTenantIsActive;
use ImovelZapAi\Tenancy\Infrastructure\Http\Middleware\ResolveTenant;

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): void {
        $middleware->trustProxies(at: '*');

        $middleware->redirectGuestsTo(function (\Illuminate\Http\Request $request) {
            if ($request->is('super-admin', 'super-admin/*') || $request->is('api/v1/super-admin', 'api/v1/super-admin/*')) {
                return route('super-admin.login');
            }

            return '/login';
        });
        $middleware->redirectUsersTo('/dashboard');

        $middleware->appendToGroup('web', RedirectIfEmailUnverified::class);

        $middleware->alias([
            'tenant.resolve' => ResolveTenant::class,
            'tenant.required' => EnsureTenantContext::class,
            'tenant.active' => EnsureTenantIsActive::class,
            'role' => EnsureRole::class,
            'platform.auth' => EnsurePlatformAuthenticated::class,
            'platform.role' => EnsurePlatformRole::class,
            'platform.mfa' => EnsurePlatformMfa::class,
            'platform.ip' => EnsurePlatformIpAllowlist::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
