<?php

use App\Http\Middleware\EnsureCompanyIsActive;
use App\Http\Middleware\EnsureModuleIsEnabled;
use App\Http\Middleware\EnsurePlanIsActive;
use App\Http\Middleware\EnsureSameCompany;
use App\Http\Middleware\ResolveTenant;
use App\Http\Middleware\RoleMiddleware;
use App\Http\Middleware\SecurityHeaders;
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',
        then: function () {
            // Cargar archivos de rutas adicionales por rol/área
            foreach ([
                'auth', 'superadmin', 'tenant', 'employee', 'customer', 'public',
            ] as $file) {
                $path = base_path("routes/{$file}.php");
                if (file_exists($path)) {
                    Illuminate\Support\Facades\Route::middleware('web')->group($path);
                }
            }
        },
    )
    ->withEvents()
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'role'             => RoleMiddleware::class,
            'tenant'           => ResolveTenant::class,
            'company.active'   => EnsureCompanyIsActive::class,
            'plan.active'      => EnsurePlanIsActive::class,
            'module'           => EnsureModuleIsEnabled::class,
            'same.company'     => EnsureSameCompany::class,
        ]);

        // ResolveTenant corre temprano en el grupo web tras la auth
        $middleware->web(append: [
            ResolveTenant::class,
            SecurityHeaders::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
