<?php

use App\Http\Middleware\EnsureAdminPortalAccess;
use App\Http\Middleware\EnsureCustomerPortalAccess;
use App\Http\Middleware\EnsureEarnEmailIsVerified;
use App\Http\Middleware\EnsureEarnMemberActive;
use App\Http\Middleware\EnsureUserIsActive;
use App\Http\Middleware\SetLocale;
use App\Support\AuthenticatedRedirect;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

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->web(append: [SetLocale::class]);
        $middleware->alias([
            'active' => EnsureUserIsActive::class,
            'customer.portal' => EnsureCustomerPortalAccess::class,
            'earn.active' => EnsureEarnMemberActive::class,
            'earn.verified' => EnsureEarnEmailIsVerified::class,
            'admin.portal' => EnsureAdminPortalAccess::class,
        ]);
        $middleware->redirectGuestsTo(fn ($request) => $request->is('earn/*') ? route('earn.login') : route('login'));
        $middleware->redirectUsersTo(fn ($request) => $request->is('earn/*') && auth('earn')->check()
            ? route('earn.dashboard')
            : app(AuthenticatedRedirect::class)->landing($request->user()));
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();
