<?php

use Illuminate\Console\Scheduling\Schedule;
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) {
        $middleware->web(append: [
            \App\Http\Middleware\HandleInertiaRequests::class,
        ]);
        $middleware->api(prepend: [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        ]);
        $middleware->alias([
            'admin'      => \App\Http\Middleware\AdminMiddleware::class,
            'admin.auth' => \App\Http\Middleware\AdminAuth::class,
        ]);
    })
    ->withSchedule(function (Schedule $schedule) {
        // Settle expired trades every minute (safety net)
        $schedule->call(function () {
            app(\App\Services\TradeService::class)->processExpiredTrades();
        })
            ->name('settle-trades')
            ->everyMinute()
            ->withoutOverlapping();

        // Also settle every 30 seconds for faster resolution
        $schedule->call(function () {
            app(\App\Services\TradeService::class)->processExpiredTrades();
        })
            ->name('settle-trades-fast')
            ->everyThirtySeconds()
            ->withoutOverlapping();
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
