<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Sentry\Laravel\Integration;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        channels: __DIR__.'/../routes/channels.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // Trust all proxies so that scheme/host/port in $request->fullUrl() are
        // resolved correctly behind a load-balancer or reverse proxy. This ensures
        // that URLs generated by route() and used in Twilio webhook signatures
        // match what Twilio actually signed.
        $middleware->trustProxies(at: '*');

        $middleware->alias([
            'platform' => App\Http\Middleware\Platform\EnsurePlatformUser::class,
            'setSolicitor' => App\Http\Middleware\Solicitor\SetSolicitorFromDomain::class,
            'ensureSolicitor' => App\Http\Middleware\Solicitor\EnsureUserBelongsToSolicitor::class,
            'passSolicitorToView' => App\Http\Middleware\Solicitor\PassTenantThroughToView::class,
            'webhook.sendgrid' => App\Http\Middleware\VerifySendGridWebhook::class,
            'webhook.twilio' => App\Http\Middleware\VerifyTwilioWebhook::class,
        ]);

        $middleware->validateCsrfTokens(except: [
            'webhook/*'
        ]);

        $middleware->web(append: [
            App\Http\Middleware\Solicitor\SetSolicitorFromDomain::class,
            App\Http\Middleware\Solicitor\PassTenantThroughToView::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        if (app()->environment('production')) { Integration::handles($exceptions); }
    })->create();
