<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Routing\Exceptions\InvalidSignatureException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        commands: __DIR__.'/../routes/console.php',
        channels: __DIR__.'/../routes/channels.php',
        health: '/up',
        then: function () {
            Route::middleware(['web'])
                ->domain(env('DOMAIN_APP', 'app.aziros.com'))
                ->group(base_path('routes/web.php'));
            Route::middleware(['api'])
                ->domain(env('DOMAIN_API', 'api.aziros.com'))
                ->group(base_path('routes/api.php'));
            Route::middleware(['web'])
                ->domain(env('DOMAIN_CONNECT', 'connect.aziros.com'))
                ->group(base_path('routes/connect.php'));
            Route::domain(env('DOMAIN_WWW', 'www.aziros.com'))
                ->group(base_path('routes/www.php'));

        }
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->validateCsrfTokens(except: [
            'stripe/webhook',
            'webhooks/google-calendar',
        ]);
        $middleware->web([
            \App\Http\Middleware\SetLocale::class,
            \App\Http\Middleware\TrackAffiliateCode::class,
            \App\Http\Middleware\CheckAppVersion::class,
        ]);
        $middleware->api([
            \App\Http\Middleware\ForceJsonResponse::class,
        ]);
        $middleware->alias([
            'auth.custom'  => \App\Http\Middleware\EnsureAuthenticated::class,
            'guest.custom' => \App\Http\Middleware\RedirectIfAuthenticatedCustom::class,
            'user'         => \App\Http\Middleware\EnsureUserIsVerified::class,
            'admin'        => \App\Http\Middleware\RoleMiddleware::class,
            'role'         => \App\Http\Middleware\RoleMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (InvalidSignatureException $e, $request) {
            return redirect()->route('verify.notice', [
                'user' => $request->route('user')
            ])->with('error.auth.verify.link_expired', t('auth.verify.link_expired'));
        });
    })->create();
