<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Support\Facades\Route;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
        then: function (): void {
            Route::domain(config('app.domains.marketing'))
                ->middleware(['web', 'track_affiliate'])
                ->group(base_path('routes/marketing.php'));

            Route::domain(config('app.domains.account'))
                ->middleware(['web', 'auth', 'verified', 'ensure_not_suspended'])
                ->group(base_path('routes/account.php'));

            Route::domain(config('app.domains.admin'))
                ->middleware(['web', 'auth', 'verified', 'role:admin|super_admin|billing_admin|support_agent|support_lead|readonly_admin'])
                ->group(base_path('routes/admin.php'));

            Route::domain(config('app.domains.account'))
                ->middleware('web')
                ->group(base_path('routes/webhooks.php'));
        },
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->trustProxies(at: '*');

        $middleware->validateCsrfTokens(except: [
            'webhooks/*',
            'api/*',
            'oauth/*',
            // Admin API endpoints for testing
            '*/settings/test-*',
        ]);

        $middleware->web(append: [
            \Illuminate\Session\Middleware\AuthenticateSession::class,
            \App\Http\Middleware\HandleInertiaRequests::class,
            \App\Http\Middleware\ScreenshotAuthMiddleware::class,
        ]);

        $middleware->prependToPriorityList(
            \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
            \App\Http\Middleware\ScreenshotAuthMiddleware::class,
        );

        $middleware->redirectGuestsTo(fn () => 'https://'.config('app.domains.account').'/login');
        $middleware->redirectUsersTo('/dashboard');

        $middleware->alias([
            'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
            'ensure_not_suspended' => \App\Http\Middleware\EnsureUserNotSuspended::class,
            'serverhunter' => \App\Http\Middleware\AllowServerHunterSpider::class,
            'track_affiliate' => \App\Http\Middleware\TrackAffiliateReferral::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
