<?php

use App\Enums\AppEnvironmentEnum;
use App\Exceptions\Auth\BlockedUserException;
use App\Exceptions\Factories\ExceptionHandlerFactory;
use App\Exceptions\Handlers\UnhandledExceptionHandler;
use App\Http\Middleware\Localization;
use App\Http\Middleware\SecuritySignatureMiddleware;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Validation\UnauthorizedException;
use Laravel\Sanctum\Http\Middleware\CheckAbilities;
use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;

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->validateCsrfTokens(except: [
            'api/v1/*', 
            'v1/*',     
            'sanctum/csrf-cookie', 
        ]);
        $middleware->alias([
            'abilities' => CheckAbilities::class,
            'ability' => CheckForAnyAbility::class,
        ]);

        $middleware->api(prepend: [
            //            SecuritySignatureMiddleware::class,
            Localization::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->dontReport([
            BlockedUserException::class,
            UnauthorizedException::class,
        ]);

        if (!App::environment(AppEnvironmentEnum::LOCAL->value)) {
            $exceptions->render(function (Throwable $e, Request $request) {
                if ($handler = ExceptionHandlerFactory::getExceptionHandler($e)) {
                    return call_user_func($handler . '::handle', $request, $e);
                }
                return UnhandledExceptionHandler::handle($request, $e);
            });
        }
    })
    ->withSchedule(function (Schedule $schedule) {
        $schedule->command('service-offers:create-from-default-templates')->everyMinute();
    })
    ->create();
