<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
            'language' => \App\Http\Middleware\SetLocal::class,
            'api_status' => \App\Http\Middleware\APIstatus::class
        ]);
        $middleware->validateCsrfTokens(except: [
            '/installation',
            'callback/mailgun',
            'callback/sendgrid',
            'callback/sparkpost',
            'callback/amazon',
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (AuthenticationException $exception, Request $request) {
            $guard = $exception->guards()[0] ?? null;
            if ($guard === 'api') {
                return response()->json(['response' => __('app.unauthenticated')], 401);
            }
        });
    })->create();
