<?php

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->alias([
            'admin.auth' => \App\Http\Middleware\AdminAuth::class,
            'admin.super' => \App\Http\Middleware\SuperAdmin::class,
            'admin.service_restrict' => \App\Http\Middleware\ServiceAdminRestrict::class,
            'admin.locale' => \App\Http\Middleware\SetAdminLocale::class,
            'wallet.auth' => \App\Http\Middleware\WalletAuth::class,
        ]);
    })
    ->withSchedule(function ($schedule): void {
        // Process AI trading bots every minute
        $schedule->command('ai-trade:process')->everyMinute();
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (\Illuminate\Session\TokenMismatchException $e, \Illuminate\Http\Request $request) {
            $message = 'Session expired. Please refresh the page and try again.';
            if ($request->expectsJson()) {
                return response()->json(['message' => $message], 419);
            }
            return redirect()->back()->withInput($request->except('password'))->with('error', $message);
        });
    })->create();
