<?php

use App\Http\Middleware\CreditCheckMiddleware;
use App\Http\Middleware\EnsureTenantAdminToken;
use App\Http\Middleware\EnsureTenantCollaboratorToken;
use App\Http\Middleware\HandleAppearance;
use App\Http\Middleware\HandleInertiaRequests;
use App\Http\Middleware\ResponseSecurityHeaders;
use App\Http\Middleware\SetLocaleFromUser;
use App\Http\Middleware\TenantIsolation;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withCommands([
        \App\Console\Commands\CheckEventPackages::class,
        \App\Console\Commands\ExportCouponRedemptions::class,
        \App\Console\Commands\DeactivateExpiredPhotoboothAccounts::class,
        \App\Console\Commands\PhotoboothIngestCommand::class,
        \App\Console\Commands\MonitorStorageCommand::class,
        \App\Console\Commands\DispatchStorageArchiveCommand::class,
        \App\Console\Commands\CheckUploadQueuesCommand::class,
        \App\Console\Commands\PurgeExpiredDataExports::class,
        \App\Console\Commands\ProcessTenantRetention::class,
        \App\Console\Commands\SendGuestFeedbackReminders::class,
        \App\Console\Commands\SyncGoogleFonts::class,
        \App\Console\Commands\SeedDemoSwitcherTenants::class,
    ])
    ->withSchedule(function (\Illuminate\Console\Scheduling\Schedule $schedule) {
        $onFailure = static function (string $command): \Closure {
            return static function () use ($command): void {
                \App\Support\SentryReporter::captureException(
                    new \RuntimeException('Scheduled command failed'),
                    [
                        'tags' => [
                            'schedule_command' => $command,
                        ],
                    ],
                );
            };
        };

        $schedule->command('package:check-status')
            ->dailyAt('06:00')
            ->onFailure($onFailure('package:check-status'));
        $schedule->command('storage:monitor')
            ->everyFiveMinutes()
            ->withoutOverlapping()
            ->onFailure($onFailure('storage:monitor'));
        $schedule->command('storage:check-upload-queues')
            ->everyFiveMinutes()
            ->withoutOverlapping()
            ->onFailure($onFailure('storage:check-upload-queues'));
        $schedule->command('storage:archive-pending')
            ->dailyAt('01:00')
            ->withoutOverlapping()
            ->onFailure($onFailure('storage:archive-pending'));
        $schedule->command('photobooth:cleanup-expired')
            ->hourly()
            ->withoutOverlapping()
            ->onFailure($onFailure('photobooth:cleanup-expired'));
        $schedule->command('photobooth:ingest')
            ->everyFiveMinutes()
            ->withoutOverlapping()
            ->onFailure($onFailure('photobooth:ingest'));
        $schedule->command('checkout:send-reminders')
            ->hourly()
            ->withoutOverlapping()
            ->onFailure($onFailure('checkout:send-reminders'));
        $schedule->command('exports:purge')
            ->dailyAt('02:00')
            ->onFailure($onFailure('exports:purge'));
        $schedule->command('tenants:retention-scan')
            ->dailyAt('03:00')
            ->onFailure($onFailure('tenants:retention-scan'));
        $schedule->command('guest:feedback-reminders')
            ->dailyAt('22:00')
            ->onFailure($onFailure('guest:feedback-reminders'));
    })
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->trustProxies(
            at: array_map('trim', explode(',', (string) env('TRUSTED_PROXIES', '*'))),
            headers: Request::HEADER_X_FORWARDED_FOR
                | Request::HEADER_X_FORWARDED_HOST
                | Request::HEADER_X_FORWARDED_PORT
                | Request::HEADER_X_FORWARDED_PROTO
                | Request::HEADER_X_FORWARDED_AWS_ELB,
        );

        $middleware->alias([
            'tenant.isolation' => TenantIsolation::class,
            'package.check' => \App\Http\Middleware\PackageMiddleware::class,
            'locale' => \App\Http\Middleware\SetLocale::class,
            'superadmin.auth' => \App\Http\Middleware\SuperAdminAuth::class,
            'credit.check' => CreditCheckMiddleware::class,
            'tenant.admin' => EnsureTenantAdminToken::class,
            'tenant.collaborator' => EnsureTenantCollaboratorToken::class,
        ]);

        $middleware->encryptCookies(except: ['appearance', 'sidebar_state']);
        $middleware->validateCsrfTokens(except: [
            'paddle/webhook',
            'paddle/webhook*',
        ]);

        $middleware->web(append: [
            \App\Http\Middleware\SetLocale::class,
            SetLocaleFromUser::class,
            HandleAppearance::class,
            ResponseSecurityHeaders::class,
            \App\Http\Middleware\ContentSecurityPolicy::class,
            HandleInertiaRequests::class,
            AddLinkHeadersForPreloadedAssets::class,
            \App\Http\Middleware\RequestTimingMiddleware::class,
        ]);

        $middleware->api(append: [
            ResponseSecurityHeaders::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
