<?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',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // Global middleware for UTF-8 encoding
        $middleware->append(\App\Http\Middleware\SetCharsetUTF8::class);
        
        $middleware->alias([
            'admin' => \App\Http\Middleware\AdminMiddleware::class,
            'member' => \App\Http\Middleware\MemberMiddleware::class,
            'seller' => \App\Http\Middleware\SellerMiddleware::class,
            'verifier' => \App\Http\Middleware\VerifierMiddleware::class,
            'community' => \App\Http\Middleware\CommunityManagerMiddleware::class,
            'accountant' => \App\Http\Middleware\AccountantMiddleware::class,
            'marketing' => \App\Http\Middleware\MarketingMiddleware::class,
            'comptabilite' => \App\Http\Middleware\ComptabiliteMiddleware::class,
            'permission' => \App\Http\Middleware\PermissionMiddleware::class,
            'locale' => \App\Http\Middleware\SetLocale::class,
            'currency' => \App\Http\Middleware\SetCurrency::class,
            'feature' => \App\Http\Middleware\CheckFeature::class,
            'subscription' => \App\Http\Middleware\SubscriptionMiddleware::class,
            'role' => \App\Http\Middleware\RoleMiddleware::class,
            '2fa' => \App\Http\Middleware\TwoFactorMiddleware::class,
            'charset' => \App\Http\Middleware\SetCharsetUTF8::class,
        ]);
        
        $middleware->validateCsrfTokens(except: [
            'api/*',
            'admin/ai/*',
            'seller/products/generate-description-ajax',
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->render(function (\Illuminate\Database\Eloquent\ModelNotFoundException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json(['error' => 'Ressource non trouvee'], 404);
            }
            return redirect()->back()->with('error', 'La ressource demandee n\'existe pas.');
        });

        $exceptions->render(function (\Illuminate\Auth\AuthenticationException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json(['error' => 'Non authentifie'], 401);
            }
            return redirect()->route('login')->with('error', 'Veuillez vous connecter.');
        });

        $exceptions->render(function (\Illuminate\Auth\Access\AuthorizationException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json(['error' => 'Acces non autorise'], 403);
            }
            return redirect()->back()->with('error', 'Vous n\'avez pas les droits pour effectuer cette action.');
        });

        $exceptions->render(function (\Illuminate\Validation\ValidationException $e, $request) {
            if ($request->expectsJson()) {
                return response()->json(['error' => 'Erreur de validation', 'errors' => $e->errors()], 422);
            }
        });
    })->create();
